Simple Chat Demo
Simple chat using the TCP protocol (very simple)
Thought: Using 2 threads, one thread is used to receive messages, and the other thread is used to send messages.
Client Demo Code:
1 Public classSenddemo {2 Public Static voidMain (string[] args)throwsexception{3Socket socket=NewSocket (Inetaddress.getlocalhost (), 8888);4Sendimpl sendimpl=NewSendimpl (socket);5 //the thread being sent6 NewThread (Sendimpl). Start ();7 //the received thread8Reciveimpl reciveimpl=NewReciveimpl (socket);9 NewThread (Reciveimpl). Start ();Ten } One A}
Server-side Demo code:
1 Public classServerdemo {2 Public Static voidMain (string[] args)throwsException {3ServerSocket ServerSocket =NewServerSocket (8888);4Socket socket=serversocket.accept ();5Sendimpl sendimpl=NewSendimpl (socket);6 NewThread (Sendimpl). Start ();7Reciveimpl reciveimpl=NewReciveimpl (socket);8 NewThread (Reciveimpl). Start ();9 }Ten One}
Demo code for the sending thread:
1 Public classSendimplImplementsrunnable{2 Privatesocket socket;3 PublicSendimpl (socket socket) {4 This. socket=socket;5 //TODO auto-generated Constructor stub6 }7 @Override8 Public voidrun () {9Scanner scanner=NewScanner (system.in);Ten while(true){ One Try { AOutputStream OutputStream =Socket.getoutputstream (); -String string=scanner.nextline (); - Outputstream.write (String.getbytes ()); the}Catch(IOException e) { - //TODO auto-generated Catch block - e.printstacktrace (); - } + } - } + A}
Demo code for the receiving thread:
1 Public classReciveimplImplementsRunnable {2 Privatesocket socket;3 PublicReciveimpl (socket socket) {4 This. socket=socket;5 //TODO auto-generated Constructor stub6 }7 @Override8 Public voidrun () {9 while(true ){Ten Try { OneInputStream InputStream =Socket.getinputstream (); A byte[] b=New byte[1024]; - intlen=Inputstream.read (b); -System.out.println ("received message:" +NewString (b,0, Len)); the -}Catch(IOException e) { - //TODO auto-generated Catch block - e.printstacktrace (); + } - } + } A at}
Simple chat for TCP implementation of Java learning notes