swing(三)----一个简单的聊天程序 博客分类: java SwingSocketJava.netthread
程序员文章站
2024-03-16 08:26:16
...
服务器端代码:
客户端
package com.cw.threadtest; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.util.List; public class ChatServer { /** * @param args */ public static void main(String[] args) { ServerSocket ss=null; try { ss = new ServerSocket(9100); } catch (IOException e) { e.printStackTrace(); } List list = new ArrayList(); while(true){ try { Socket s = ss.accept(); list.add(s); Thread t = new ChatServerThread(s,list); t.start(); } catch (IOException e) { e.printStackTrace(); } } } } class ChatServerThread extends Thread{ Socket socket ; List list; BufferedReader in ; public ChatServerThread(Socket socket, List list) { super(); this.socket = socket; this.list = list; } @Override public void run() { try { in = new BufferedReader(new InputStreamReader(socket.getInputStream())); while(true){ String text = in.readLine(); if (text==null)break; for(int i=0;i<list.size();i++){ Socket socket2 = (Socket) list.get(i); PrintWriter out = new PrintWriter(socket2.getOutputStream()); out.println(text); out.flush(); } } } catch (IOException e) { e.printStackTrace(); }finally{ list.remove(socket); } } }
客户端
package com.cw.threadtest; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import java.net.UnknownHostException; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; public class ChatClient { JFrame frame ; JTextField jtf ; JTextArea jta; BufferedReader in ; PrintWriter out; public ChatClient() { frame = new JFrame(""); frame.setSize(300, 300); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jtf = new JTextField(); jta = new JTextArea(); frame.add(jtf,"South"); frame.add(new JScrollPane(jta)); jta.setEditable(false); frame.setVisible(true); Socket s; try { s =new Socket("192.168.1.11",9100); out = new PrintWriter(s.getOutputStream()); in = new BufferedReader(new InputStreamReader(s.getInputStream())); jtf.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent arg0) { String text = jtf.getText(); jtf.setText(""); out.println(text); out.flush(); } }); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public void receiveText(){ while(true){ try { String text = in.readLine(); jta.append(text+"\n"); } catch (IOException e) { e.printStackTrace(); } } } public static void main(String[] args) { ChatClient cc = new ChatClient(); cc.receiveText(); } }