package chen.chat;
import java.io.*;
import java.net.*;publicclassServer
{publicstaticvoidmain(String [] agrs)
{try{
ServerSocket server=newServerSocket(4000);
System.out.println("服务器开启");while(true)
{
Socket client=server.accept();try{
System.out.println("客户已经连接到服务器
");
System.out.println("IP:"+client.getInetAddress().getHostAddress()+"Port:"+client.getPort());newServerThread(client).start();
}catch(Exception e)
{
e.printStackTrace();
}
}
}catch(IOException e)
{
e.printStackTrace();
}
}
}classServerThread extends Thread
{privateSocket client ;privateBufferedReader bfSystemInput;privateBufferedReader bfSocketInput;privatePrintWriter outer;publicServerThread(Socket socket)
{try{this.client=socket;this.bfSystemInput=newBufferedReader(newInputStreamReader(System.in));this.bfSocketInput=newBufferedReader(newInputStreamReader(this.client.getInputStream()));this.outer=newPrintWriter(this.client.getOutputStream());
}catch(IOException e)
{
e.printStackTrace();
}
}publicvoidrun()
{
ListernerSystem lstSocket=newListernerSystem(this.bfSocketInput);
ListenerSystem lstSystem=newListenerSystem(this.bfSystemInput,this.outer);
lstSocket.start();
lstSystem.start();
}
}classListernerSystem extends Thread
{privateBufferedReader bfSocketInput;publicListernerSystem(BufferedReader bf)
{this.bfSocketInput=bf;
}publicvoidrun()
{while(true)
{
String msg=null;try{if((msg=bfSocketInput.readLine())!=null)
{
System.out.println("Your friend say:"+msg);
}else{
System.out.println("dsa");
}
}catch(IOException e)
{
e.printStackTrace();
}
}
}
}classListenerSystem extends Thread
{privateBufferedReader bfSystemInput;privatePrintWriter outer;publicListenerSystem(BufferedReader bf,PrintWriterout)
{this.bfSystemInput=bf;this.outer=out;
}publicvoidrun()
{while(true)
{try{
String msg=null;if((msg=bfSystemInput.readLine())!=null)
{this.outer.println("You Say:"+msg);
}else{
System.out.println("dsa");
}
}catch(IOException e)
{
e.printStackTrace();
}
}
}
}