package java_learning;
import java.net.*;
import java.util.*;
import java.io.*;
class ChatServer_test {
ServerSocket server = null;
Collection cclient = new ArrayList();//客户端 socket 列表
//构造函数
public ChatServer_test(int port) throws Exception{
server = new ServerSocket(port);
}
//@SuppressWarnings("unchecked")
public void startServer() throws Exception{
while(true){
Socket s = server.accept();
cclient.add(new ClientThread(s));
}
}
//内部类
class ClientThread implements Runnable{
Socket s = null;
//构造函数
public ClientThread(Socket s){
this.s = s;
(new Thread(this)).start();
}
public void run(){
try{
DataInputStream dis = new DataInputStream(s.getInputStream());
//读入一个已使用 UTF-8 修改版格式编码的字符串。
String str = dis.readUTF();
while(str != null && str.length() != 0){
System.out.println(str);
str = dis.readUTF();//为什么又重新读,循环重新读
}
}catch(IOException e){
System.out.println("client quit");
try {
if(s != null)
s.close();
cclient.remove(this);
} catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
}
public static void main(String[]args) throws Exception{
ChatServer_test cs = new ChatServer_test(8888);//新建一个ServerSocket
cs.startServer();//接受一个socket,建立一个线程来处理该socket事件
}
}