Multi-person chat room realized by multithreading +socket

Source: Internet
Author: User

Recently in the Learning Multi-threading plan to do a simple multi-threaded Socke chat program, the results found that the code on the Internet does not have a complete implementation function, so I realized a demo:

The demo function is basically, there is a server responsible for information forwarding, multiple clients send messages, when a client sends a message, other clients can be accepted.

Service side:

Client:

Client code:

 Packagecom.cky.client;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.io.PrintWriter;ImportJava.net.Socket;Importjava.net.UnknownHostException;ImportJava.util.Scanner; Public classClient {PrivatePrintWriter out; //private BufferedReader BR;    PrivateScanner Scan; PrivateBoolean flag=true; PrivateSocket S; PrivateInputStream is;  PublicClient ()throwsUnknownhostexception, IOException {s=NewSocket ("127.0.0.1", 5001); is=S.getinputstream (); }         Public Static voidMain (String []args)throwsUnknownhostexception, IOException {client client=NewClient ();    Client.startup (); }     Public voidStartup ()throwsunknownhostexception, IOException { out=NewPrintWriter (S.getoutputstream (),true); //open a thread to listen for messages on the serverThread ct=NewThread (NewRunnable () {@Override Public voidrun () { while(true) {                    if(!flag) Break; Try{receive (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace ();        }                }            }        });        Ct.start (); //The main thread is responsible for sending messagesSystem.out.println ("Please enter your user name:"); Scan=NewScanner (system.in); String name=Scan.nextline ();        OUT.PRINTLN (name); SYSTEM.OUT.PRINTLN (Name+ ", welcome to the chat room, enter quit Quit");  while(flag) {String Read=Scan.nextline (); if(Read.equalsignorecase ("Quit") ) {flag=false; }            //System.out.println (read);out.println (read);    } s.close (); }         Public voidReceive ()throwsIOException {bytess[]=New byte[1024]; intLength=S.getinputstream (). read (ss); System.out.println (NewString (ss,0, length)); }}

Service-Side code:

 PackageCom.cky.server;ImportJava.io.BufferedReader;Importjava.io.IOException;ImportJava.io.InputStreamReader;ImportJava.io.PrintWriter;ImportJava.net.ServerSocket;ImportJava.net.Socket;Importjava.util.ArrayList;Importjava.util.List; Public classServer {PrivateList<threadserver> clients=NewArraylist<threadserver>();  Public voidStartup ()throwsIOException {System.out.println ("Listening on port 5001"); ServerSocket SS=NewServerSocket (5001);  while(true) {Socket Socket=ss.accept (); System.out.println ("Discover new users"); Thread St=NewThread (Newthreadserver (socket));        St.start (); }    }         Public classThreadserverImplementsrunnable{Privatesocket socket; PrivateBufferedReader BR; PrivatePrintWriter out; PrivateString name; PrivateBoolean flag=true;  PublicThreadserver (Socket socket)throwsIOException { This. socket=socket; BR=NewBufferedReader (NewInputStreamReader (Socket.getinputstream ())); out=NewPrintWriter (Socket.getoutputstream (),true); String Str=Br.readline (); Name=str+ "[" +socket.getinetaddress (). Gethostaddress () + ":" +socket.getport () + "]"; SYSTEM.OUT.PRINTLN (Name+ "Join this chat room"); Send (name+ "Join this chat room"); Clients.add ( This); }        Private voidSend (String message) { for(Threadserver threadserver:clients) {System.out.println ("--Send Message to Thread" +threadserver.name+ ");                ThreadServer.out.print (message);            ThreadServer.out.flush (); }        }        Private voidReceive ()throwsIOException {String message;  while(flag=true) {Message=Br.readline (); if(Message.equalsignorecase ("Quit") {System.out.println ("User" +name+ "exited"); Out.println ("Quit");                    Out.flush (); Clients.remove ( This); Flag=false; } System.out.println (Name+":"+message); Send (name+":"+message); }} @Override Public voidrun () {Try {                 while(flag=true) {receive (); }            } Catch(IOException e) {e.printstacktrace (); }finally {                Try{socket.close (); } Catch(IOException e) {e.printstacktrace (); }            }        }    }         Public Static voidMain (String []args)throwsIOException {Server server=NewServer (); System.out.println ("Server Open");    Server.startup (); }    }

Start the server, listen to the port, and then use the client login to send the message.

Multi-person chat room realized by multithreading +socket

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.