1. 程式人生 > >Java建立聊天客戶端(三)

Java建立聊天客戶端(三)

(平時操作,留下痕跡,以後效,君若受益,吾之大幸)

一、MainWindow.class

package cn.upc.chatclient.view;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.border.EmptyBorder;

import cn.upc.chatclient.main.ChatManager;

public class MainWindow extends JFrame {

   private static final long serialVersionUID = 1L;
   private JPanel contentPane;
   JTextArea txt;
   private JTextField ip;
   private JTextField words;


   public MainWindow() {
      setAlwaysOnTop(true);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setBounds(100, 100, 450, 300);
      contentPane = new JPanel();
      contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
      setContentPane(contentPane);
      
      txt = new JTextArea();
      txt.setText("Ready...");
      
      ip = new JTextField();
      ip.setText("180.201.154.112");
      //ip.setColumns(10);

      JButton button = new JButton("連線到伺服器");
      button.addMouseListener(new MouseAdapter() {
         @Override
         public void mouseClicked(MouseEvent arg0) {
            ChatManager.getCM().connect(ip.getText());
         }
      });
      
      words = new JTextField();
      words.setText("");
      words.setColumns(10);
      
      JButton button_1 = new JButton("傳送");
      button_1.addMouseListener(new MouseAdapter() {
         @Override
         public void mouseClicked(MouseEvent arg0) {
            ChatManager.getCM().send(words.getText());
            appendText("我說:"+words.getText());
            words.setText(""); //clean
         }
      });
      GroupLayout gl_contentPane = new GroupLayout(contentPane);
      gl_contentPane.setHorizontalGroup(
         gl_contentPane.createParallelGroup(Alignment.LEADING)
            .addGroup(Alignment.TRAILING, gl_contentPane.createSequentialGroup()
               .addGroup(gl_contentPane.createParallelGroup(Alignment.TRAILING)
                  .addGroup(gl_contentPane.createSequentialGroup()
                     .addContainerGap()
                     .addComponent(txt, GroupLayout.DEFAULT_SIZE, 434, Short.MAX_VALUE))
                  .addGroup(gl_contentPane.createSequentialGroup()
                     .addContainerGap()
                     .addComponent(ip, GroupLayout.DEFAULT_SIZE, 306, Short.MAX_VALUE)
                     .addPreferredGap(ComponentPlacement.RELATED)
                     .addComponent(button))
                  .addGroup(gl_contentPane.createSequentialGroup()
                     .addComponent(words, GroupLayout.DEFAULT_SIZE, 272, Short.MAX_VALUE)
                     .addPreferredGap(ComponentPlacement.RELATED)
                     .addComponent(button_1, GroupLayout.PREFERRED_SIZE, 162, GroupLayout.PREFERRED_SIZE)))
               .addContainerGap())
      );
      gl_contentPane.setVerticalGroup(
         gl_contentPane.createParallelGroup(Alignment.LEADING)
            .addGroup(gl_contentPane.createSequentialGroup()
               .addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE)
                  .addComponent(ip, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                  .addComponent(button))
               .addPreferredGap(ComponentPlacement.RELATED)
               .addComponent(txt, GroupLayout.DEFAULT_SIZE, 196, Short.MAX_VALUE)
               .addPreferredGap(ComponentPlacement.RELATED)
               .addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE)
                  .addComponent(words, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                  .addComponent(button_1)))
      );
      contentPane.setLayout(gl_contentPane);
   }

   
   public void appendText(String in) {
      txt.append("\n"+in);
   }
}

 

二、StartClient.class

package cn.upc.chatclient.main;

import java.awt.EventQueue;

import cn.upc.chatclient.view.MainWindow;

public class StartClient {

   public static void main(String[] args) {
      EventQueue.invokeLater(new Runnable() {
         public void run() {
            try {
               MainWindow frame = new MainWindow();
               frame.setVisible(true);
               ChatManager.getCM().setWindow(frame);
            } catch (Exception e) {
               e.printStackTrace();
            }
         }
      });
   }

}

 

三、ChatManager.class

package cn.upc.chatclient.main;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import cn.upc.chatclient.view.MainWindow;


public class ChatManager {

   private ChatManager(){}
   private static final ChatManager instance = new ChatManager();
   public static ChatManager getCM() {
      return instance;
   }
   
   MainWindow window;
   String IP;
   Socket socket;
   BufferedReader reader;
   PrintWriter writer;
   
   public void setWindow(MainWindow window) {
      this.window = window;
   }
   
   public void connect(String ip) {
      this.IP = ip;
      new Thread(){

         @Override
         public void run() {
            try {
               socket = new Socket(IP, 12345);
               window.appendText("連線成功!");
               writer = new PrintWriter(
                     new OutputStreamWriter(
                           socket.getOutputStream()));
               
               reader = new BufferedReader(
                     new InputStreamReader(
                           socket.getInputStream()));
               String line;
               while ((line = reader.readLine()) != null) {
                  window.appendText("收到:"+line);
               }
               writer.close();
               reader.close();
               writer = null;
               reader = null;
            } catch (UnknownHostException e) {
               e.printStackTrace();
            } catch (IOException e) {
               window.appendText("連線失敗!");
            }
         }
      }.start();
   }
   
   public void send(String out) {
      if (writer != null) {
         writer.write(out+"\n");
         writer.flush();
      }else {
         window.appendText("(傳送內容不可為空)");
      }
   }
}