import java.net.*;import java.io.*;public classChatserver {boolean started=false;
ServerSocket ss=null;//初始化
public static voidmain(String[] args) {newChatserver().start();
}public voidstart()
{try{
ss=new ServerSocket(8888);//端口号8888,TCP
started=true;//连接上
}catch(BindException e){
System.out.println("端口使用中");
System.exit(0);
}catch(IOException e){
e.printStackTrace();//给出方法的调用程序,一直到异常的产生位置
}try{while(started)
{boolean bConnected=false;
Socket s=ss.accept();
Client c=new Client(s);//把s传进去 main是静态的,Client是动态的,在静态的方法NEW一个动态的类不行每来一个new一个新的线程
System.out.println("a client connected!");new Thread(c).start();//让这个线程启动
/*bConnected=true;//接收到对方之后变成true
dis=new DataInputStream(s.getInputStream());
while(bConnected){//有东西来就读
String str=dis.readUTF();//阻塞式
System.out.println(str);*/}//dis.close();
}catch(IOException e) {
e.printStackTrace();
}finally{try{
ss.close();
}catch(IOException e){
e.printStackTrace();
}
}/*catch (EOFException e){
System.out.println("Client closed!");
}
catch (IOException e) {
e.printStackTrace();
}finally{
try{
if(dis !=null) dis.close();
//if(s !=null) s.close();
}catch(IOException e1){
e1.printStackTrace();
}
}*/}
}class Client implements Runnable{//线程内部类
privateSocket s;private DataInputStream dis=null;//每个客户端都保有自己的inputStream;//保留有自己的连接
private boolean bConnected=false;public Client(Socket s){//传递Socket这个属性,构造函数
this.s=s;try{
dis=newDataInputStream(s.getInputStream());
bConnected=true;//连上以后等于TRUE
} catch(IOException e) {//TODO Auto-generated catch block
e.printStackTrace();
}
}public voidrun(){//接收到对方之后变成true
try{while(bConnected){//有东西来就读
String str=dis.readUTF();//阻塞式,接受客户端给我的字符串且打印
System.out.println(str);
}
}catch(EOFException e){
System.out.println("Client closed!");
}catch(IOException e) {
e.printStackTrace();
}finally{try{if(dis !=null) dis.close();//if(s !=null) s.close();
}catch(IOException e1){
e1.printStackTrace();
}
}
}
}