多线程聊天程序

package com.zl.chatTwo;


 
  //服务端
import java.io.*;   
import java.net.*;   
import java.util.*;   
public class ChatServer {   
    public static void main(String args[]) {   
        Hashtable<String,DataOutputStream> userList = new Hashtable<String,DataOutputStream>();    
        String name;   
        DataInputStream dis;   
        DataOutputStream dos;   
        try{
 
            ServerSocket ss = new ServerSocket(9999);   
             
            while(true){   
                Socket s = ss.accept();    
                dis = new DataInputStream(s.getInputStream());   
                dos = new DataOutputStream(s.getOutputStream());   
                name = dis.readUTF();      
                userList.put(name,dos); 
                new MyServerReader(name,dis,userList).start();   
            }   
        }catch(Exception e){   
            e.printStackTrace();       
        }   
    }   
}   
  
class MyServerReader extends Thread{   
    private String name;   
    private DataInputStream dis;   
    private Hashtable<String,DataOutputStream> userList;   
    public MyServerReader(String name,DataInputStream dis,Hashtable<String,DataOutputStream> userList ){   
        this.name = name;   
        this.dis = dis;    
        this.userList = userList;   
    }   
    public void run(){   
        String info;   
        try{   
            transmitMessage(name + " in!","--Server Info--");      
            while(true){   
                info = dis.readUTF();   
                if(info.equals("bye")){   
                    DataOutputStream dos = (DataOutputStream)(userList.get(name));   
                    Thread.sleep(1000);   
                    dos.close();   
                    dis.close();   
                    userList.remove(name);   
                    transmitMessage(name + " out!","--Server Info--");     
                    break;   
                }else if(info.length()>0){   
                    transmitMessage(info,name);    
                }   
            }          
        }catch (Exception e) {   
        }   
    }    
    public void transmitMessage(String msg,String name){   
        Collection doses = userList.values();   
        DataOutputStream dos;   
        for(Object o: doses){   
            dos = (DataOutputStream)o;   
             
            try{   
                dos.writeUTF(name + ":" + msg); 
            }catch(Exception e){   
            }   
            
        }              
    } 
    
   
    
}  
//客户端

package com.zl.chatTwo;
import java.io.*;   
import java.net.*;   
import java.awt.*;   
import java.awt.event.*;   
public class ChatClient {   
    private String name;   
    private Socket s;   
    private DataInputStream dis;   
    private DataOutputStream dos;   
    private Frame f;   
    private TextArea ta;   
    private TextField tf;   
    private boolean runnable = true;       
           
    public static void main(String args[]) {   
        ChatClient cc = new ChatClient();    
        cc.createUI(); 
        
        cc.inputName(); 
        
        cc.connect(); 
        
        cc.createThread();   
    }   
 
    public void createUI(){  
     
        f = new Frame("Client"); 
        ta = new TextArea();
         
        ta.setEditable(false); 
        tf = new TextField();  
        Button send = new Button("Send");    
        Panel p = new Panel();    
        p.setLayout(new BorderLayout());   
        p.add(tf,"Center");   
        p.add(send,"East");   
        f.add(ta,"Center");   
        f.add(p,"South");
         
        MyClientListener listener = new MyClientListener(this);  
        
 
        send.addActionListener(listener);   
         
        tf.addActionListener(listener);  
         
        f.addWindowListener(new WindowAdapter(){   
            public void windowClosing(WindowEvent e){   
                ChatClient.this.shutDown();    
            }      
        });    
        f.setSize(400,400);
         
        f.setLocation(600,0);    
        f.setVisible(true);
         
        tf.requestFocus();   
    }
    
     
    public void inputName(){   
        String name = javax.swing.JOptionPane.showInputDialog("Input Your Name:");   
        this.setName(name);    
        f.setTitle(name);   
    }  
    
 
    public void connect(){   
        try {          
            s = new Socket("127.0.0.1",9999);   
            dos = new DataOutputStream(s.getOutputStream());   
            dis = new DataInputStream(s.getInputStream());   
            dos.writeUTF(name);   
        }catch (IOException e) {   
            e.printStackTrace();           
        }   
    }    
 
    public void createThread(){   
        MyClientReader reader = new MyClientReader(this);   
        reader.start();    
    }    
    public void stop(){   
        runnable = false;      
    }   
 
    public void shutDown(){   
        try{   
            dos.writeUTF("bye");   
            ta.append("Exit in 5 seconds!");   
            this.stop();               
            Thread.sleep(5000);   
            dis.close();   
            dos.close();   
            s.close();   
        }catch(Exception e){   
        }   
        System.exit(0);                        
    }
    
 
    public boolean getRunnable(){   
        return runnable;   
    }              
    public void setName(String name){   
        this.name = name;   
    }   
    public DataInputStream getDataInputStream(){   
        return dis;    
    }   
    public DataOutputStream getDataOutputStream(){   
        return dos;    
    }   
    public TextArea getTextArea(){   
        return ta;     
    }   
    public TextField getTextField(){   
        return tf;     
    }   
}   
  

 
class MyClientListener implements ActionListener{   
       
    private ChatClient client;     
    public MyClientListener(ChatClient client){   
        this.client = client;   
    }   
    public void actionPerformed(ActionEvent e){   
        TextField tf = client.getTextField();   
        String info = tf.getText();   
        try{   
            client.getDataOutputStream().writeUTF(info);       
        }catch (IOException e1) {   
            e1.printStackTrace();          
        }   
        if(info.equals("bye")){   
            client.shutDown();     
        }    
        tf.setText("");   
         
        tf.requestFocus();         
    }      
} 
 
class MyClientReader extends Thread{   
    private ChatClient client;   
    public MyClientReader(ChatClient client){   
        this.client = client;      
    }   
    public void run(){   
        String info;   
        DataInputStream dis = client.getDataInputStream();   
        TextArea ta = client.getTextArea();   
        try{   
            while(client.getRunnable()){   
                info = dis.readUTF();   
                ta.append(info + "\n");   
            }          
        }catch (IOException e) {   
        }      
    }   
}  


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值