package chat.client;import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.EOFException;import java.io.IOException;import java.net.ServerSocket;import java.net.Socket;import java.net.SocketException;import java.util.ArrayList;import javax.swing.BorderFactory;import javax.swing.DefaultListModel;import javax.swing.JList;import javax.swing.JPanel;import javax.swing.JScrollPane;import javax.swing.border.BevelBorder;public class ChatServer { static ServerSocket ss = null; static boolean started = false; static Socket s; static ArrayList<Client> clients; JPanel panel; static DefaultListModel model; JList list; public static void main(String[] args) throws IOException { new ChatServer(); ss = new ServerSocket(9999); System.out.println("Waiting for client to connect..."); started = true; clients = new ArrayList<Client>(); while (started) { s = ss.accept(); System.out.println("A client connected!"); Client c = new Client(s); clients.add(c); new Thread(c).start(); System.out.println("目前在线人数:"+clients.size()); } } public ChatServer() { super(); panel=new JPanel(); model=new DefaultListModel(); list=new JList(model); list.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED)); panel.add(new JScrollPane(list)); } static class Client implements Runnable { private boolean bConnect = false; private DataInputStream dis = null; private DataOutputStream dos = null; private Socket s; public Client(Socket s) { super(); this.s = s; try { dis = new DataInputStream(s.getInputStream()); dos = new DataOutputStream(s.getOutputStream()); } catch (IOException e) { e.printStackTrace(); } } @Override public void run() { boolean bConnected = true; while (bConnected) { try { String str = dis.readUTF(); for (int i = 0; i < clients.size(); i++) { Client c1 = clients.get(i); c1.send(str); } } catch (EOFException e) { System.out.println("一个client端已经退出"); clients.remove(this); System.out.println("目前在线人数:"+clients.size()); try { dis.close(); dos.close(); s.close(); } catch (IOException e1) { e1.printStackTrace(); } bConnected = false; } catch (SocketException e) { clients.remove(this); System.out.println("client端已经退出"); System.out.println("目前在线人数:"+clients.size()); try { dis.close(); dos.close(); s.close(); } catch (IOException e1) { e1.printStackTrace(); } bConnected = false; } catch (IOException e) { e.printStackTrace(); } } } public void send(String str) { try { dos.writeUTF(str); } catch (IOException e) { e.printStackTrace(); } } }}
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货