Chat tools that implement the functions of private chat and group chat

Source: Internet
Author: User


As mentioned in the previous blog (simple C/S chat room), we have adopted the multi-thread method. The main thread on the server is responsible for continuously listening on the port, and the subthread is responsible for receiving and sending messages. The main thread of the client needs to receive keyboard messages and send them to the server. The subthread needs to receive messages sent from the server. In the implementation of this simple C/S chat room, only the group chat function is implemented, and private chat is not implemented. In this article, we will talk about private chat and group chat.


First of all, how do I know whether a message is a public chat or a private chat. Therefore, the message must be processed. For example, some special characters must be added before and after the message, which is called protocol characters. Therefore, we can define an interface specifically to define protocol characters.

The second problem is that if it is private chat information, the client will send the target user (Private Chat object) to the server, how will the server find the target user. Here, it is obvious that we need to establish a user-socket ing relationship, so we use map, but here we need to improve the map, in fact, we can't just repeat the key, nor duplicate the value. We also need to find the key through the value, so we have made improvements.

Another point that needs to be pointed out for this implementation is that the server sub-thread is responsible for receiving and sending messages. This also includes determining whether the user name is repeated when the client establishes a connection for the first time, that is to say, to ensure that the key is not repeated, the client needs to keep trying when establishing the connection for the first time until the provided name is not repeated.

The Code is as follows:


Public interface crazyitprotocol {public static final int protocol_len = 2; // The default type is public static final. If this parameter is not added, public static final string msg_round = "△role" is also supported "; public static final string usr_round = "□☆"; public static final string login_success =" ☆? "; Public static final string name_rep ="-1 "; public static final string pravite_round =" ◆★"; Public static final string split_sign = "? ";}

Import Java. util. hashmap; import Java. util. hashset; import Java. util. set; public class crazyitmap <K, V> extends hashmap <K, V> {// Delete the specified public void removebyvalue (object Value) {for (Object key: keyset () {If (get (key) = value | get (key ). equals (value) {remove (key); break ;}}// obtain the public set of values <v> valueset () {set <v> result = new hashset <v> (); For (Object key: keyset () {result. add (get (key);} return result;} // rewrite the PUT Method of hashmap. This method does not allow repeated public v put (K key, V value) values) {for (v val: valueset () {If (val = value | Val. equals (value) {Throw new runtimeexception ("duplicate value is not allowed in mymap instance") ;}} return Super. put (Key, value);} // search for keypublic K getkeybyvalue (object Value) {for (K key: keyset () {If (get (key) = value | get (key ). equals (value) {return key ;}} return NULL ;}}

Import Java. io. ioexception; import Java. io. printstream; import java.net. serversocket; import java.net. socket; public class server {Private Static final int Port = 30000; public static crazyitmap <string, printstream> clients = new crazyitmap <> (); void Init () {try (serversocket Ss = new serversocket (port);) {While (true) {socket S = ss. accept (); New thread (New serverthread (s )). start () ;}} catch (ioexception e) {// todo Au To-generated catch blocksystem. Out. println ("failed to start the server. Is the port occupied? ") ;}} Public static void main (string [] ARGs) {// todo auto-generated method stubserver S = new server (); S. INIT ();}}

Import Java. io. bufferedreader; import Java. io. ioexception; import Java. io. inputstreamreader; import Java. io. printstream; import java.net. socket; public class serverthread implements runnable {private socket s; private bufferedreader BR = NULL; private printstream PS = NULL; Public serverthread (socket s) {This. S = s ;}@ overridepublic void run () {// todo auto-generated method stubtry {BR = new bufferedreader (new input Streamreader (S. getinputstream (); PS = new printstream (S. getoutputstream (); string content = NULL; while (content = Br. Readline ())! = NULL) {If (content. startswith (crazyitprotocol. usr_round) // The name and content are sent. startswith (crazyitprotocol. usr_round) {string username = getrealmsg (content); If (server. clients. containskey (username) // duplicate name {system. out. println ("repeated"); PS. println (crazyitprotocol. name_rep);} else // The name is unique {system. out. println ("successful"); server. clients. put (username, PS); PS. println (crazyitprotocol. login_success) ;}} else if (content. start Swith (crazyitprotocol. pravite_round) & content. startswith (crazyitprotocol. pravite_round) // The actual message is sent, and it is a private chat message {string userandmsg = getrealmsg (content); string username = userandmsg. split (crazyitprotocol. split_sign) [0]; string MSG = userandmsg. split (crazyitprotocol. split_sign) [1]; // gets the output stream server of the private chat user. clients. get (username ). println (server. clients. getkeybyvalue (PS) + "" + MSG);} else // public chat information {string MSG = getrealm SG (content); For (printstream PS: Server. clients. valueset () {ps. println (server. clients. getkeybyvalue (this. PS) + "said:" + MSG) ;}}// capture exception, indicating that the client corresponding to the socket has encountered a problem, // The client deletes the catch (ioexception e) {// todo auto-generated catch blockserver from the map. clients. removebyvalue (PS); try {If (BR! = NULL) {Br. Close () ;}if (PS! = NULL) {ps. Close () ;}if (s! = NULL) {S. close () ;}} catch (ioexception ex) {ex. printstacktrace () ;}}// remove the Protocol characters before and after the lecture, and restore the private string getrealmsg (string content) to the actual data) {// todo auto-generated method stubreturn content. substring (crazyitprotocol. protocol_len, content. length ()-crazyitprotocol. protocol_len );}}

Import Java. io. bufferedreader; import Java. io. ioexception; import Java. io. inputstreamreader; import Java. io. printstream; import java.net. socket; import java.net. unknownhostexception; import javax. swing. joptionpane; public class client {Private Static final int Port = 30000; private socket S = NULL; private printstream PS = NULL; private bufferedreader brserver = NULL; // Private bufferedreader keyin = NULL ;/ /Enter public void Init () {try {S = new socket ("127.0.0.1", Port); PS = new printstream (S. getoutputstream (); keyin = new bufferedreader (New inputstreamreader (system. in); brserver = new bufferedreader (New inputstreamreader (S. getinputstream (); // used to log on to the server, because the name may be repeated string tip = ""; while (true) {string username = joptionpane. showinputdialog (TIP + "enter user name"); // Add the Protocol string before and after the user's user name, and then send ps. println (crazyitprotocol. usr_round + us Ername + crazyitprotocol. usr_round); string result = brserver. readline (); If (result. equals (crazyitprotocol. name_rep) {tip = "the user name already exists. Please try again"; Continue ;}// if (result. equals (crazyitprotocol. login_success) {break ;}} catch (unknownhostexception ex) {system. out. println ("the remote server cannot be found. Please make sure the server is started! "); Closers (); system. Exit (1);} catch (ioexception ex) {system. Out. println (" network exception! Log on again! "); Closers (); system. exit (1);} new thread (New clientthread (brserver); // The subthread is responsible for receiving messages sent from the server.} private void closers () {// todo auto-generated method stubtry {If (keyin! = NULL) {keyin. Close ();} If (brserver! = NULL) {brserver. Close () ;}if (PS! = NULL) {ps. Close () ;}if (s! = NULL) {S. close () ;}} catch (ioexception e) {e. printstacktrace () ;}// Keyboard Message receiving function of the main thread public void readandsend () {string content = NULL; try {While (content = keyin. readline ())! = NULL) {// The message is sent starting with "/". If yes, it is considered as a private chat. If (content. startswith ("/") & content. indexof (":")> 0) {content = content. substring (1); // The message does not need to start with/content = crazyitprotocol. pravite_round + content. split (":") [0] + crazyitprotocol. split_sign + content. split (":") [1] + crazyitprotocol. pravite_round; PS. println (content);} else // group chat information {content = crazyitprotocol. msg_round + content + crazyitprotocol. msg_round; PS. println (content) ;}} catch (IOE Xception e) {system. Out. println ("Network Communication exception! Log on again! "); Closers (); system. exit (1) ;}} public static void main (string [] ARGs) {// todo auto-generated method stubclient client = new client (); client. init (); client. readandsend ();}}

import java.io.BufferedReader;import java.io.IOException;public class ClientThread implements Runnable {private BufferedReader brServer=null;public ClientThread(BufferedReader brServer){this.brServer=brServer;}@Overridepublic void run() {// TODO Auto-generated method stubString content=null;try{while((content=brServer.readLine())!=null){System.out.println(content);}}catch(IOException e){e.printStackTrace();}finally{try{if(brServer!=null){brServer.close();}}catch(IOException e){e.printStackTrace();}}}}

Reference: Java crazy handout


Chat tools that implement the functions of private chat and group chat

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.