Java Socket Multi-person chat room implementation

Source: Internet
Author: User

Implementation features

Server-side:

1. The server can monitor multiple socket connections.

2. The server forwards the received message to all socket connections.

Client:

1, the client listens to the message from the server in real time.

2. Clients can send messages to the server at any time.

Solution Ideas

The server listens to multiple connections in a circular wait, each time a new thread processing connection is enabled, the connection is established to a list, and each time the message is received, the array forwarding message is traversed to achieve the purpose of broadcasting to all clients.

The client uses two threads, one thread is responsible for receiving information in real time, and one thread is responsible for sending the information in real time.

Key code

Server Multithreading Listener Client connection:

1 Try {2      while(true) {3         //Accept () will block the thread4Socket socket =serversocket.accept ();5 6         //Save Connection7 Sockets.add (socket);8 9         //enable new thread handlingTen         NewThread (Newhandlerconnection (socket, sockets)). Start (); One     } A}Catch(Exception e) { -SYSTEM.OUT.PRINTLN ("Connect client failed:" +e.tostring ()); -}
Listen Clients

The server forwards the message to all clients:

1 printwriter PrintWriter;2 Try {3      for(Socket socket:sockets) {4PrintWriter =NewPrintWriter (Socket.getoutputstream (),true);5 printwriter.println (message);6     }7}Catch(Exception e) {8System.out.println ("[sendtoclients]" +e.tostring ());9}
Send Clients

The client listens for messages returned by the server side:

1  Public voidrun () {2 BufferedReader Reader;3     Try {4Reader =NewBufferedReader (NewInputStreamReader (Socket.getinputstream ()));5          while(true) {6Thread.Sleep (10);7 System.out.println (Reader.readline ());8         }9}Catch(Exception e) {TenSystem.out.println ("[Receive message failed]" +e.tostring ()); One     } A}
Receive Server

The client sends a message to the server:

1  Public voidrun () {2Scanner Scanner =NULL;3PrintWriter PrintWriter =NULL;4     Try {5Scanner =NewScanner (system.in);6PrintWriter =NewPrintWriter (Socket.getoutputstream (),true/*Auto Flush*/);7 8Boolean EOF =false;9          while(!eof &&Scanner.hasnext ()) {TenString message =scanner.nextline (); OnePrintwriter.println ("Client-1:" +message); A             if(Quit.equals (Message.trim ())) { -EOF =true; -             } the         } -}Catch(IOException e) { -System.out.println ("[Send message failed]" +e.tostring ()); -}finally { +         //Close Resource -         if(NULL!=scanner) { + scanner.close (); A         } at         if(NULL!=PrintWriter) { - printwriter.close (); -         } -         Try { - socket.close (); -}Catch(IOException e) { inSystem.out.println ("[Close client socket failed]" +e.tostring ()); -         } to     } +}
Send ServerTest

Start a server, two clients, the effect is as follows:

Full code path: Https://github.com/vicis-zyzy/SocketDemo

Java Socket Multi-person chat room implementation

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.