Simple socket communication for private chat, group chat (DOS command)

Source: Internet
Author: User

A long time ago a demo, where the server only do forwarding function, based on the ID address and port number to identify identity, group chat and private chat is simply implemented,

The server code is as follows:

ImportJava.util.*;ImportJava.io.*;Importjava.net.*; Public classServerextendsThread {Private StaticVector<socket> vecclient =NewVector<socket>(); PrivatePrintWriter out; PrivateBufferedReader in; PrivateSocket Clientsocket;  Public Static voidMain (string[] args)throwsIOException {serversocket server=NewServerSocket (2014);//CreateSystem.out.println ("Start the server! ");        Socket sock;  while(true) {sock= Server.accept ();//waiting for customer requestServer ser =NewServer (sock); Ser.start (); //Start        }    }     PublicServer (socket socket) { This. Clientsocket =socket; Vecclient.addelement (socket); //Adding a client thread to an array        Try {            //get the word stream from the server, save it to the buffer .in =NewBufferedReader (NewInputStreamReader (Socket.getinputstream ())); //PrintWriter, the text output stream prints the formatted representation of the object, only calls println and so on, automatic refresh is true, forcing the data output of the buffer. out =NewPrintWriter (NewOutputStreamWriter (Socket.getoutputstream ()),true); //input, OutputStreamWriter is a bridge of character flow to byte stream}Catch(IOException e) {}} Public voidrun () {Try{newclient (); //send a welcome message to a new customer informing all online customers that a new customer is connected             while(true)//handle communication with customers{String msg=in.readline ();//Data Read                                if(Msg.equals ("Bye") | | msg.equals ("Bye"))//exit when input is goodbye or bye{Xiaxian ();          In.close (); //close the input streamClientsocket.close ();//Close Socket                     Break; }                Else if(Msg.indexof ("@") ==0&&msg.indexof ("") >0){                    intEnd=msg.indexof (""); String findaddr=msg.substring (1, end); if(Vecclient.isempty () = =false)//judged to be empty                        {                         for(intI=0;i<vecclient.size (); i++) {Socket Socket=Vecclient.get (i); String Addr= Socket.getinetaddress (). toString (). Replace ("/", "") + ":" +Socket.getport (); if(findaddr.equals (addr)) {String ADDR2= Clientsocket.getinetaddress (). toString (). Replace ("/", "") + ":" +Clientsocket.getport (); //ElementAt Returns the component at the specified index, and get returns the element at the specified position in the listPrintWriter PW =NewPrintWriter (NewOutputStreamWriter (Vecclient.get (i). Getoutputstream ()),true); Pw.println ("The Great God" +addr2+ "said to you:" +msg.substring (end)); }                        }                        }                }                //Otherwise, the received information will be sent to all online customers .                Else                {                    if(Vecclient.isempty () = =false)                          for(intI=0;i<vecclient.size (); i++)                        {                            //ElementAt Returns the component at the specified index, and get returns the element at the specified position in the listPrintWriter PW =NewPrintWriter (NewOutputStreamWriter (Vecclient.get (i). Getoutputstream ()),true); Pw.println ("Great God" +clientsocket.getinetaddress (). toString () + ":" +clientsocket.getport () + "say:" +msg); }                }            }        }        Catch(IOException e) {}} Public voidNewclient ()throwsIOException//new, with this function{String addr= Clientsocket.getinetaddress (). toString () + ":" +Clientsocket.getport (); Out.println ("Welcome:" + addr+ "Join!" "); Try {            if(Vecclient.isempty () = =false)                 for(inti = 0; I < vecclient.size (); i++) {Socket Socket=Vecclient.get (i); PrintWriter PW=NewPrintWriter (NewOutputStreamWriter (Socket.getoutputstream ()),true); String ADDR2= Socket.getinetaddress (). toString () + ":" +Socket.getport (); if(Addr.equals (ADDR2)) {pw.println ("Welcome to join the chat, private chat please use @ip:port content"); } Else{pw.println ("New member:" +clientsocket.getinetaddress (). toString ()+ ":" + clientsocket.getport () + "Hey, get up!" "); }                }        } Catch(IOException e) {}} Public voidXiaxian ()throwsIOException//Downline Method{out.println ("Good-bye, the connection is off!" "); if(Vecclient.isempty () = =false)             for(inti = 0; I < vecclient.size (); i++) {PrintWriter pw=NewPrintWriter (NewOutputStreamWriter (vecclient. Get (i). Getoutputstream ()),true); Pw.println ("--" +clientsocket.getinetaddress (). toString ()+ ":" + clientsocket.getport () + "already offline");     } vecclient.remove (Clientsocket); }}
View Code

Customer service, you can run multiple tests in the local command, private chat format: @ip:p ort (there must be spaces) content, the principle is as follows:

Importjava.net.*;ImportJava.io.*;ImportJava.util.*;classclient{ Public Static voidMain (string[] args) {Try{Socket Socket=NewSocket ("localhost", 2014); Clientsend Send=NewClientsend (socket);//Create send threadClientreceive receive=NewClientreceive (socket);//Create a Receive threadSend.start ();//Start send threadReceive.start ();//start the Receive thread          }        Catch(Exception e) {System.out.println ("The server is not turned on!" ");          E.printstacktrace (); }                       }}classClientsendextendsthread{Privatesocket socket; PrivatePrintWriter out;  Publicclientsend (socket socket) { This. socket=socket; Try{ out=NewPrintWriter (NewOutputStreamWriter (Socket.getoutputstream ()),true); //returns the output stream of a server with a client, true forcing the data output of the buffer        }        Catch(IOException e) {e.printstacktrace (); }    }         Public voidRun ()//send message to server{String msg; Scanner input=NewScanner (system.in);//inputmsg = Input.nextline ();//The nextline method returns all characters before the carriage return         while(true)        {            //use Equalsignorecase to ignore case            if(Msg.equals ("Bye") | | msg.equals ("bye")) {out.println (msg);  Break;            } out.println (msg); Msg=Input.nextline (); }    }}classClientreceiveextendsThread//Receive{    Privatesocket socket; PrivateBufferedReader in;  Publicclientreceive (socket socket) { This. socket=socket; Try{ in=NewBufferedReader (NewInputStreamReader (Socket.getinputstream ())); }        Catch(IOException e) {e.printstacktrace (); }    }         Public voidRun ()//receive information from the server    {                Try{String msg=In.readline ();  while(Msg.equals ("bye") = =false) {System.out.println (msg); Msg=In.readline ();            } in.close ();        Socket.close (); }        Catch(IOException e) {e.printstacktrace (); }            }}
View Code

Simple socket communication for private chat, group chat (DOS command)

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.