[java]代码库
import java.net.*;
import java.util.*;
import java.io.*;
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(8999);
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{
transimitMessage(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);
transimitMessage(name+"out","--Server Info--");
break;
}else if(info.length()>0){
transimitMessage(info,name);
}
}
}catch(Exception e){
e.printStackTrace();
}
}
public void transimitMessage(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){
e.printStackTrace();
}
}
}
}
高级设计师
by: 由月君 发表于:2013-10-26 16:11:26 顶(1) | 踩(0) 回复
沙发
回复评论