TXT

ChatServer

By Jeanne Grant,2014-07-17 04:53
8 views 0
ChatServer

    import java.awt.BorderLayout; import java.awt.TextArea; import java.io.*;

    import java.net.*;

    import java.util.*;

    import javax.swing.JFrame; import javax.swing.JTextArea;

public class ChatServer extends JFrame{

     TextArea Text;

     public ChatServer(){

     Text = new TextArea();

     add(Text);

     setTitle("Server");

     setBounds(400, 50, 360, 420);

     setVisible(true);

     Text.append("服务器开始监听3270端口\n");

     }

     boolean started = false;

     ServerSocket ss = null;

     List<Client> clients = new ArrayList<Client>();

     public static void main(String[] args) {

     new ChatServer().start();

     }

     public void start() {

     try {

     ss = new ServerSocket(3270);

     started = true;

     } catch (IOException e) {

     e.printStackTrace();

     }

     try {

     while(started) {

     Socket s = ss.accept();

     Client c = new Client(s);

     Text.append("一个客户端连接上来了\n");

     new Thread(c).start();

     clients.add(c);

     //dis.close();

     }

     } catch (IOException e) {

     e.printStackTrace();

     } finally {

     try {

     ss.close();

     } catch (IOException e) {

     e.printStackTrace();

     }

     }

     }

     class Client implements Runnable {

     private Socket s;

     private DataInputStream dis = null;

     private DataOutputStream dos = null;

     private boolean bConnected = false;

     public Client(Socket s) {

     this.s = s;

     try {

     dis = new DataInputStream(s.getInputStream());

     dos = new DataOutputStream(s.getOutputStream());

     bConnected = true;

     } catch (IOException e) {

     e.printStackTrace();

     }

     }

     public void send(String str) {

     try {

     dos.writeUTF(str);

     } catch (IOException e) {

     clients.remove(this);

     Text.append("对方退出;从List里面去掉;\n");

     //e.printStackTrace();

     }

     }

     public void run() {

     try {

     while(bConnected) {

     String str = dis.readUTF();

     Text.append(str+"\n");//服务器断输出客户端发来的信息

     for(int i=0; i<clients.size(); i++) {

     Client c = clients.get(i);

     c.send(str);

     }

     }

     } catch (EOFException e) {

     Text.append("客户端关闭了\n");

     } catch (IOException e) {

     e.printStackTrace();

     } finally {

     try {

     if(dis != null) dis.close();

     if(dos != null) dos.close();

     if(s != null) {

     s.close();

     }

     } catch (IOException e1) {

     e1.printStackTrace();

     }

     }

     }

     }

    }

Report this document

For any questions or suggestions please email
cust-service@docsford.com