Please indicate the source for reprinting. Thank you!
Today, I want to share with you the core code of the server and client in my QQ project, and talk about some of my suggestions and opinions. I hope you can provide more support, this is the motivation for my continued sharing. Haha!
I. server. Well, let's take a look at the server part. I will use the thread pool here. As for why the thread pool is used, if you do not know about shoes, go to another blog: http://blog.csdn.net/weidi1989/article/details/7930820. When a user connects, we will immediately drop the user's socket into the established thread pool for processing, so that we can quickly free up time to accept the connection of the next user, the thread in the thread pool is split into two threads, one is the reading thread and the other is the writing thread. Of course, because I use this chat to forward messages, therefore, a map is created in singleton mode to store the message writing thread of each user (if there are many users, this is a considerable resource consumption), so that when the message is forwarded, the map key can be used to retrieve the corresponding user's message writing thread, so as to forward messages. Let's talk about the details below.
/*** Server, accepting user logon, offline, and message forwarding ** @ author way **/public class server {private executorservice; // thread pool private serversocket = NULL; private Socket socket = NULL; private Boolean isstarted = true; // whether to wait cyclically for public server () {try {// create a thread pool, which has (CPU x 50) thread executorservice = executors. newfixedthreadpool (runtime. getruntime (). availableprocessors () * 50); serversocket = new serversocket (Co Nstants. server_port);} catch (ioexception e) {e. printstacktrace (); quit () ;}} public void start () {system. out. println (mydate. getdatecn () + "the server has been started... "); try {While (isstarted) {socket = serversocket. accept (); string IP = socket. getinetaddress (). tostring (); system. out. println (mydate. getdatecn () + "User:" + IP + "established connection"); // to support concurrent access by multiple users, the thread pool is used to manage the connection requests of each user if (socket.isconnected(execuutorservice.exe cute (New Sockettask (socket); // Add to thread pool} If (socket! = NULL) // After the loop ends, remember to close the socket and release the resource socket. Close (); If (serversocket! = NULL) serversocket. close ();} catch (ioexception e) {e. printstacktrace (); // isstarted = false;} private final class sockettask implements runnable {private Socket socket = NULL; private inputthread in; private outputthread out; private outputthreadmap map; public sockettask (Socket socket) {This. socket = socket; Map = outputthreadmap. getinstance () ;}@ overridepublic void run () {out = new outputthread (socket, MAP); // instantiate the message writing thread first, (store the corresponding user's write thread in the map cache) in = new inputthread (socket, out, MAP); // instantiate the read message thread out. setstart (true); In. setstart (true); In. start (); out. start () ;}}/*** exit */Public void quit () {try {This. isstarted = false; serversocket. close ();} catch (ioexception e) {e. printstacktrace () ;}} public static void main (string [] ARGs) {new server (). start ();}}
II. The server writes the message thread. Next, let's take a look at the message writing thread. It's a simple piece of code with comments, so I won't say much about it:
/*** Write message thread ** @ author way **/public class outputthread extends thread {private outputthreadmap map; private objectoutputstream OOS; private tranobject object; private Boolean isstart = true; // loop flag private Socket socket; Public outputthread (Socket socket, outputthreadmap map) {try {This. socket = socket; this. map = map; OOS = new objectoutputstream (socket. getoutputstream (); // instantiate the object output stream in the constructor} catch (IO Exception e) {e. printstacktrace () ;}} public void setstart (Boolean isstart) {// used to close the write thread externally this. isstart = isstart;} // call the message writing thread. After the message is set, wake up the run method to save resources: Public void setmessage (tranobject object) {This. object = object; synchronized (this) {Policy () ;}@ overridepublic void run () {try {While (isstart) {// when no message is written, the thread waits for synchronized (this) {Wait () ;}if (object! = NULL) {OOS. writeobject (object); OOS. Flush () ;}} if (OOS! = NULL) // After the loop ends, close the stream and release the resource OOS. Close (); If (socket! = NULL) socket. Close () ;}catch (interruptedexception e) {e. printstacktrace () ;}catch (ioexception e) {e. printstacktrace ();}}}
III. The server writes the message thread cache. Let's take a look at the true view of the message writing thread cache:
/*** The cache for storing write threads ** @ author way */public class outputthreadmap {private hashmap <integer, outputthread> map; Private Static outputthreadmap instance; // private constructor to prevent external instantiation from changing to private outputthreadmap () {map = new hashmap <integer, outputthread> ();} // The Singleton mode provides the public synchronized static outputthreadmap getinstance () {If (instance = NULL) {instance = new outputthreadmap ();} return instance ;} // Add write thread method public synchronized void add (integer ID, outputthread out) {map. put (ID, out);} // method for removing the write thread public synchronized void remove (integer ID) {map. remove (ID);} // method for getting the write thread. For group chat, you can traverse and retrieve the corresponding write thread public synchronized outputthread getbyid (integer ID) {return map. get (ID) ;}// get all write thread methods, used to send broadcast public synchronized list <outputthread> getall () to all online users () {list <outputthread> List = new arraylist <outputthread> (); For (map. entry <integer, outputthread> entry: map. entryset () {list. add (entry. getvalue () ;}return list ;}}
4. The server reads the message thread, followed by the read message thread, which consists of two parts: reading the message and processing the message. I paste the Code separately, although I wrote it in a class:
/*** Message reading thread and processing method ** @ author way **/public class inputthread extends thread {private Socket socket; // socket object private outputthread out; // The message writing thread passed in, because we want to reply the message to the user. Private outputthreadmap map; // write the message thread cache private objectinputstream OIS; // object input stream private Boolean isstart = true; // whether to cyclically read the message public inputthread (Socket socket, outputthread out, outputthreadmap map) {This. socket = socket; this. out = out; this. map = ma P; try {OIS = new objectinputstream (socket. getinputstream (); // instantiated object input stream} catch (ioexception e) {e. printstacktrace () ;}} public void setstart (Boolean isstart) {// provides an interface to the external end the reading thread this. isstart = isstart;} @ overridepublic void run () {try {While (isstart) {// read the message readmessage ();} If (OIS! = NULL) Ois. Close (); If (socket! = NULL) socket. Close ();} catch (classnotfoundexception e) {e. printstacktrace ();} catch (ioexception e) {e. printstacktrace ();}}
5. Server Message Processing: The following is a method for message processing. Due to the troubles and various confusions, I separate the message processing thread and paste it a little more concise:
/*** Read and process the message and throw an exception ** @ throws ioexception * @ throws classnotfoundexception */Public void readmessage () throws ioexception, classnotfoundexception {object readobject = Ois. readobject (); // read the object userdao Dao = userdaofactory from the stream. getinstance (); // manage the background if (readobject! = NULL & readobject instanceof tranobject) {tranobject read_tranobject = (tranobject) readobject; // convert it to the transfer object switch (read_tranobject.gettype () {case register: // if the user is registered with registeruser = (User) read_tranobject.getobject (); int registerresult = Dao. register (registeruser); system. out. println (mydate. getdatecn () + "New User Registration:" + registerresult); // send a message to the user. tranobject <user> register2tranobject = new tranobject <User> (tranobjecttype. register); User register2user = new user (); register2user. setid (registerresult); register2tranobject. setobject (register2user); out. setmessage (register2tranobject); break; Case login: User loginuser = (User) read_tranobject.getobject (); arraylist <user> List = Dao. login (loginuser); tranobject <arraylist <user> login2object = new tranobject <arraylist <user> (tranobjecttype. login); If (list! = NULL) {// tranobject <user> onobject = new tranobject <user> (tranobjecttype. login); User login2user = new user (); login2user. setid (loginuser. GETID (); onobject. setobject (login2user); For (outputthread onout: map. getall () {onout. setmessage (onobject); // broadcast the user online} map. add (loginuser. GETID (), OUT); // broadcast first, and then store the write thread of the corresponding user ID into the map, so that login2object is called when the message is forwarded. setobject (list); // Add the friend list to the reply object} else {login2object. set Object (null);} Out. setmessage (login2object); // returns the logon information to the user system. out. println (mydate. getdatecn () + "User:" + loginuser. GETID () + "online"); break; Case logout: // if it is exited, update the online status of the database, and send a group message to all online users: User logoutuser = (User) read_tranobject.getobject (); int offid = logoutuser. GETID (); system. out. println (mydate. getdatecn () + "User:" + offid + "offline"); Dao. logout (offid); isstart = false; // end your read loop map. remove (offid); // slave Remove out from the stored thread. setmessage (null); // you must first set an empty message to wake up the write thread out. setstart (false); // end the write thread loop tranobject <user> offobject = new tranobject <user> (tranobjecttype. logout); User logout2user = new user (); logout2user. setid (logoutuser. GETID (); offobject. setobject (logout2user); For (outputthread offout: map. getall () {// broadcast the offline message offout of the user. setmessage (offobject);} break; Case message: // if the message is forwarded (you can add a group) // obtain the ID of the object to be forwarded in the message, then obtain the written line of the cached object. Process int Id2 = read_tranobject.gettouser (); outputthread toout = map. getbyid (Id2); If (toout! = NULL) {// if the user is online toout. setmessage (read_tranobject);} else {// if it is null, it indicates that the user is offline and the user textmessage text = new textmessage (); text. setmessage ("dear! The recipient is not online. Your message will be temporarily stored on the server "); tranobject <textmessage> offtext = new tranobject <textmessage> (tranobjecttype. message); offtext. setobject (text); offtext. setfromuser (0); out. setmessage (offtext);} break; Case Refresh: List <user> refreshlist = Dao. refresh (read_tranobject.getfromuser (); tranobject <list <user> refresho = new tranobject <list <user> (tranobjecttype. refresh); refresho. setobject (refreshlist); out. setmessage (refresho); break; default: Break ;}}}
Well, the core code of the server is like this. Is it very simple? Yes, because we still have a lot of things to do, such as heartbeat monitoring whether users are always online and releasing resources if they are not online. These are all issues that must be taken into account in commercial projects, as for whether the user is online through heartbeat monitoring, let me talk about some of my ideas: the client regularly sends a heartbeat packet to the server (preferably an empty packet to save traffic ), the server also regularly monitors the heartbeat packet. If the heartbeat packet of the client is not received three times, the server determines that the user has dropped the line and released resources, it depends on the situation. If you have any better suggestions, please leave a message. Thank you.
6. message transmission object. Let's take a look at this super message object and the defined message type:
/*** Transmission object, maximum object transmitted directly through socket ** @ author way */public class tranobject <t> implements serializable {/***/Private Static final long serialversionuid = 1l; private tranobjecttype type; // type of the message sent: Private int fromuser; // the user's private int touser; // the user's private t object to which the message is sent; // the object to be transmitted, this object can be customized to any private list <integer> group; // users who send a group to get... set...
/*** Transfer object type ** @ author way **/Public Enum tranobjecttype {register, // register login, // log on to logout, // log off to log on to friendlogin, // friend goes online to friendlogout, // friend goes offline to message, // The user sends the message unconnected, // the file cannot be connected, // transfer the file refresh, // refresh the friend list}
7. The client, and then the client, is similar to the server, but there is no thread pool established because it is unnecessary, right? There is no sequential order between the instantiated write thread and the read thread. This is just a difference ~ Haha
/*** Client ** @ author way **/public class client {private Socket Client; private clientthread; private string IP; private int port; Public client (string IP, int port) {This. IP = IP; this. port = port;} public Boolean start () {try {client = new socket (); // client. connect (New inetsocketaddress (constants. server_ip, // constants. server_port), 3000); client. connect (New inetsocketaddress (IP, port), 3000); If (client. isconnected () {// system. out. println ("connected .. "); clientthread = new clientthread (client); clientthread. start () ;}} catch (ioexception e) {e. printstacktrace (); Return false;} return true;} // directly obtain the read thread public clientinputthread getclientinputthread () {return clientthread through the client. getin () ;}// get the write thread public clientoutputthread getclientoutputthread () {return clientthread directly through the client. getout () ;}// directly stop reading and writing messages through the client public void setisstart (Boolean isstart) {clientthread. getin (). setstart (isstart); clientthread. getout (). setstart (isstart);} public class clientthread extends thread {private clientinputthread in; private clientoutputthread out; Public clientthread (Socket socket) {In = new clientinputthread (socket ); out = new clientoutputthread (socket);} public void run () {In. setstart (true); out. setstart (true); In. start (); out. start () ;}// get the read message thread public clientinputthread getin () {return in ;}// get the write message thread public clientoutputthread getout () {return out ;}}}
8. client-side message writing thread. Check the client-side message writing thread first:
/*** Client message writing thread ** @ author way **/public class clientoutputthread extends thread {private Socket socket; private objectoutputstream OOS; private Boolean isstart = true; private tranobject MSG; public clientoutputthread (Socket socket) {This. socket = socket; try {OOS = new objectoutputstream (socket. getoutputstream ();} catch (ioexception e) {e. printstacktrace () ;}} public void setstart (Boolean isstart) {th Is. isstart = isstart;} // The Public void setmsg (tranobject MSG) {This. MSG = MSG; synchronized (this) {Policy () ;}@ overridepublic void run () {try {While (isstart) {If (MSG! = NULL) {OOS. writeobject (MSG); OOS. flush (); If (MSG. getType () = tranobjecttype. logout) {// if the message is offline, the loop break will jump out directly;} synchronized (this) {Wait (); // after the message is sent, thread enters the waiting status} OOS. close (); // close the output stream and socketif (socket! = NULL) socket. Close () ;}catch (interruptedexception e) {e. printstacktrace () ;}catch (ioexception e) {e. printstacktrace ();}}}
9. The client reads the message thread, and then the client reads the message thread. Here is another note. Do we need to tell the user when we receive the message? How to tell? Interface listening seems to be a good way, Shenma? Do not know interface listening? Will you use the setonclicklistener of Android? This is the click event listening encapsulated by Android. If you don't understand it, you can take a good look. It is not difficult to understand it:
/*** Client message reading thread ** @ author way **/public class clientinputthread extends thread {private Socket socket; private tranobject MSG; private Boolean isstart = true; private objectinputstream OIS; private messagelistener; // message listening interface object public clientinputthread (Socket socket) {This. socket = socket; try {OIS = new objectinputstream (socket. getinputstream ();} catch (ioexception e) {e. printstacktrace () ;}}/*** Method for external message listening ** @ Param messagelistener * message listening interface object */Public void setmessagelistener (messagelistener) {This. messagelistener = messagelistener;} public void setstart (Boolean isstart) {This. isstart = isstart;} @ overridepublic void run () {try {While (isstart) {MSG = (tranobject) Ois. readobject (); // each time a message is received, the method of the interface is called and the message object is passed in. When the method of the interface is implemented externally, you can process the incoming message objects in time. // I don't know if I have any instructions? Messagelistener. Message (MSG);} Ois. Close (); If (socket! = NULL) socket. close ();} catch (classnotfoundexception e) {e. printstacktrace ();} catch (ioexception e) {e. printstacktrace () ;}/ *** message listening interface ** @ author way **/public interface messagelistener {public void message (tranobject MSG );}}
Okay, the copy is finished. If you have any questions or suggestions, please leave a message. Remember: Your support is the motivation for me to continue. Haha