Java socket Programming--chat small case

Source: Internet
Author: User
Tags readline sendmsg

A long time ago wrote the socket chat room, are almost forgotten, the impulse to write again.

Server-side:

 Packagecom.fancy;ImportJava.io.BufferedReader;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.io.InputStreamReader;ImportJava.io.OutputStream;ImportJava.io.PrintWriter;ImportJava.net.ServerSocket;ImportJava.net.Socket;ImportJava.util.HashMap;ImportJava.util.Map; Public classServer {Private intPort; PrivateServerSocket server; Privatemap<string,printwriter> clients =NewHashMap ();  PublicServer ()throwsIOException {Port= 10025; Server=NewServerSocket (port); System.out.println ("Successfully created server side!");    Startreceive (); }     Public voidStartreceive ()throwsioexception{ while(true) {Socket Socket=server.accept (); //inetaddress address = socket.getinetaddress ();ClientHandler handler =NewClientHandler (socket); NewThread (handler). Start (); }    }     Public voidsendmsg (String from,string str)throwsIOException { for(String k:clients.keyset ()) {if(K.equals (from)) {Continue; } printwriter PW=Clients.get (k);            Pw.println (str);        Pw.flush (); }    }    classClientHandlerImplementsrunnable{PrivateString Nickname; Privatesocket socket; PrivatePrintWriter PW;  PublicClientHandler (socket socket) { This. Socket =socket; } @Override Public voidrun () {BufferedReader br=NULL; Try{InputStream in=Socket.getinputstream (); BR=NewBufferedReader (NewInputStreamReader (in)); OutputStream out=Socket.getoutputstream (); PW=NewPrintWriter (out,true); String name=Br.readline ();  This. Nickname =name; if(!Clients.containskey (name))                    {clients.put (name, PW); Pw.println ("Welcome new friends:" +name+ ", Current online number:" +clients.size ());                } String str;  while(str = br.readline ())! =NULL){                    if("Exit". Equalsignorecase (Str.trim ())) {Clients.remove ( This. Nickname);  This. Socket.close (); Sendmsg ("All", This. nickname+ "offline, current online number:" +clients.size ()); }Else{sendmsg (name,name+ ":" +str); }                }            } Catch(Exception e) {e.printstacktrace (); } finally{                Try{br.close (); } Catch(IOException e) {}}} }     Public Static voidMain (string[] args) {Try{Server s=NewServer (); } Catch(IOException e) {e.printstacktrace (); }    }}
View Code

Client:

 Packagecom.fancy;ImportJava.io.BufferedReader;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.io.InputStreamReader;ImportJava.io.OutputStream;ImportJava.io.PrintWriter;ImportJava.net.Socket;Importjava.net.UnknownHostException;ImportJava.util.Scanner; Public classClient {Privatesocket socket; Private BooleanOnline =true;  PublicClient ()throwsunknownhostexception, IOException {socket=NewSocket ("127.0.0.1", 10025); OutputStream out=Socket.getoutputstream (); PrintWriter PW=NewPrintWriter (out,true); Scanner Scan=NewScanner (system.in);        String Word; Serverhandler hander=NewServerhandler (); NewThread (hander). Start (); System.out.println ("Please enter your nickname:"); Word=Scan.nextline ();        PW.PRINTLN (word);        Pw.flush ();  while((Word=scan.nextline ())! =NULL) {pw.println (word);            Pw.flush (); if("Exit". Equalsignorecase (word)) {Online=false;  Break; }        }    }    classServerhandlerImplementsrunnable{@Override Public voidrun () { while(online) {InputStream in; Try{ in=Socket.getinputstream (); BufferedReader BR=NewBufferedReader (NewInputStreamReader (in)); String Back=Br.readline ();                System.out.println (back); } Catch(IOException e) {e.printstacktrace (); }            }        }    }     Public Static voidMain (string[] args) {Try{Client C=NewClient (); System.out.println ("Started!"); } Catch(unknownhostexception e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); }            }}
View Code

Run the server one time, the results of multiple clients are as follows:

  

Java socket Programming--chat small case

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.