当前位置: 代码迷 >> J2SE >> .建立一个服务监听和多个客户端,模拟多人聊天程序解决方法
  详细解决方案

.建立一个服务监听和多个客户端,模拟多人聊天程序解决方法

热度:69   发布时间:2016-04-24 12:14:41.0
.建立一个服务监听和多个客户端,模拟多人聊天程序
求代码


------解决方案--------------------
package com.tsing.chat.frame;

 

import java.io.ObjectInputStream;


public class ClientThread implements Runnable {

ClientFrame frame;
public ClientThread(ClientFrame frame){
this.frame=frame;
}
 
public void run() {
 
try {
while(true){ 
ObjectInputStream objin =new ObjectInputStream(frame.socket.getInputStream());
MsgBean bean=(MsgBean) objin.readObject(); 
// 得到的信息往窗体上的list里写,list会自动更新显示
frame.list.add( bean.getSource()+" 说: "+bean.getInfo()+"\n"); 

} catch (Exception e) {
e.printStackTrace();
}

}
 
}




package com.tsing.chat.frame;


import java.io.Serializable;

public class MsgBean implements Serializable{

String type;
String source;
String target;
String info;
 
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getTarget() {
return target;
}
public void setTarget(String target) {
this.target = target;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}


}

package com.tsing.chat.server;


import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Hashtable;

import com.tsing.thread.ServerThread;
 

public class Server { 

Hashtable allsocket=new Hashtable (); 

public Server(){

try {
ServerSocket serverSocket=new ServerSocket(9000); 
while(true) {
Socket socket= serverSocket.accept();
//启动线程
new Thread(new ServerThread(allsocket,socket)).start();

} catch (IOException e) { 
e.printStackTrace();
}
 
}


public static void main(String[] args) {
new Server();
}


}




  相关解决方案