Java Socket Chat Room Programming (ii) the use of socket to achieve a single chat room _java

Source: Internet
Author: User
Tags flush getmessage gettext readline tojson

In the article Java Socket Chat room programming (i) the use of socket to implement chat message push we talked about how to use the socket to allow the server and the client to pass messages between the message to achieve the purpose of the push message, and then I will write out how to let the server establish client and client communication.

In fact, it is to establish a one-to-one chat communication.

And the last implementation of the message push the code is somewhat different, modified above it.

If the method or class is not mentioned is exactly the same as the previous one.

1, modify entity classes (server side and client entity classes are the same)

1,userinfobean User Information table

public class Userinfobean implements Serializable {
private static final long serialversionuid = 2L;
Private long userid;//User ID
private string username;//user name
private string likename;//nickname
private String Userp wd;//user Password
private String usericon;//user avatar
//Omit Get, set method
}

2,messagebean Chat Information table

public class Messagebean implements Serializable {
private static final long serialversionuid = 1L;
Private long messageid;//Message ID
private long groupid;//Group ID
Private Boolean isgoup;//is a group message
private int Chatt ype;//message type; 1, text; 2, picture; 3, small video; 4, file; 5, geographic location; 6, voice; 7, Video Call
private string content;//text message content
private string errormsg //error message
private int errorcode;//error code
private int userid;//user ID
private int friendid;//target Buddy ID
Private Messagefilebean chatfile;//message attachment
//Omit Get, set method
}

3,messagefilebean Message Attachment table

public class Messagefilebean implements Serializable {
private static final long serialversionuid = 3L;
private int fileid;//file ID
private String filename;//file name
private long filelength;//file length
private byte[] filebyte;//file Content
private string filetype;//file type
private string filetitle;//file header name
//ellipsis Get, set method
}

2, (server-side code modification) Chatserver The main Chat service class, modify

public class Chatserver {//Socket service private static serversocket server;///use ArrayList to store all Socket public list<socket
> socketlist = new arraylist<> ();
Imitates the Socket public map<integer stored in memory, socket> socketmap = new HashMap ();
Imitate the user information stored in the database public Map<integer, userinfobean> userMap = new HashMap ();
Public Gson Gson = new Gson (); /** * Initialize socket service/public void Initserver () {try {///Create a ServerSocket to monitor client requests on port 8080 = new ServerSocket (socketurl
S.port);
CreateMessage ();
catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();}}
/** * Create message management, always receive message/private void CreateMessage () {try {System.out.println ("Wait for user access:");
Use Accept () to block waiting for a client to request a socket socket = server.accept ();
Save the linked socket in the collection to Socketlist.add (socket);
SYSTEM.OUT.PRINTLN ("User access:" + socket.getport ()); Open a child thread to wait for another socket to join new thread (new Runnable () {public void run () {//again create a socket service to wait for other users to access CreateMessage ();}).
Start ();
For server push message to User getMessage (); //Get information from the client BufferedReader BFF = new BufferedReader (New InputStreamReader (Socket.getinputstream ()));
Read Send to server info String line = null;
The loop always receives messages from the current socket while (true) {thread.sleep;//System.out.println ("content:" + bff.readline ()); Get information for the client while (line = Bff.readline ())!= null) {//Parse entity class Messagebean Messagebean = Gson.fromjson (line, MESSAGEBEAN.C
LASS);
Add user information into the map, imitate add into the database and memory//entity classes into the database, socket into memory, all with the user ID as the reference setchatmap (Messagebean, socket);
Forwards the message sent in by the user to the target buddy Getfriend (Messagebean);
System.out.println ("User:" + usermap.get (Messagebean.getuserid ()). GetUserName ());
System.out.println ("content:" + messagebean.getcontent ());}}
Server.close ();
catch (Exception e) {//TODO auto-generated catch block E.printstacktrace ();
System.out.println ("Error:" + e.getmessage ());}} /** * Send message */private void GetMessage () {New Thread (new Runnable () {public void run () {try {String buffer; true {//Enter BufferedReader from console Strin = new BufferedReader (new InputStreamReader (S)ystem.in));
Buffer = Strin.readline ();
Because the ReadLine is the end point of the line break, add the line to the end of buffer + = "\ n"; This is modified to push messages to all users connected to the server for (Socket socket:socketMap.values ()) {OutputStream output = Socket.getoutputstream (); output
. Write (Buffer.getbytes ("Utf-8"));
Send data Output.flush ();
(IOException e) {//TODO auto-generated catch block E.printstacktrace ();}}
). Start (); /** * Simulate adding information into database and memory * * @param messagebean * @param scoket/private void Setchatmap (Messagebean messagebean, Socket Scoket) {//Save user information if (userMap!= null && usermap.get (Messagebean.getuserid ()) = = null) {Usermap.put (Messagebe
An.getuserid (), Getuserinfobean (Messagebean.getuserid ())); ////(Socketmap!= null && socketmap.get (Messagebean.getuserid ()) = = null) {Socketmap.put (M
Essagebean.getuserid (), scoket); /** * Simulate database user information, create user information with different ID * * @param userId * @return/private Userinfobean getuserinfobean (int userId) {User
Infobean Userinfobean = new Userinfobean (); UserInfoBean.setusericon ("User Avatar");
Userinfobean.setuserid (USERID);
Userinfobean.setusername ("admin");
Userinfobean.setuserpwd ("123123132a");
return Userinfobean; /** * Forwards the message to the target buddy * * @param messagebean/private void Getfriend (Messagebean messagebean) {if (Socketmap!= null
;& Socketmap.get (Messagebean.getfriendid ())!= null) {Socket socket = Socketmap.get (Messagebean.getfriendid ());
String buffer = Gson.tojson (Messagebean);
Because the ReadLine is the end point of the line break, add the line to the end of buffer + = "\ n"; try {//Send information to client outputstream output = Socket.getoutputstream (); Output.write (Buffer.getbytes ("Utf-8"));//Send data output.
Flush ();
catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();}} }
}

3, (client code) loginactivity login page modification can log in multiple people

public class Loginactivity extends Appcompatactivity {private EditText chat_name_text, chat_pwd_text; private Button Cha
T_LOGIN_BTN; @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (
R.layout.activity_login);
Chat_name_text = (edittext) Findviewbyid (R.id.chat_name_text);
Chat_pwd_text = (edittext) Findviewbyid (R.id.chat_pwd_text);
CHAT_LOGIN_BTN = (Button) Findviewbyid (R.ID.CHAT_LOGIN_BTN); Chat_login_btn.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) {int status = GetLog
In (Chat_name_text.gettext (). ToString (). Trim (), Chat_pwd_text.gettext (). ToString (). Trim ()); if (status = = 1 | | | status = 0) {toast.maketext (loginactivity.this, "Password error", Toast.length_long). Show (); return;} getchat
Server (GetLogin () (Chat_name_text.gettext (). ToString (). Trim (), Chat_pwd_text.gettext (). ToString (). Trim ());
Intent Intent = new Intent (loginactivity.this, Mainactivity.class);
StartActivity (Intent); Finish ();
}
}); /** * Return to login status, 1 for the user, 2 for another user, here simulate two users communicate with each other * * @param name * @param pwd * @return * * Private int GetLogin (String name, Stri ng pwd) {if (Textutils.isempty (name) | | 
Textutils.isempty (pwd)) {return 0;//did not enter full password} else if (name.equals ("admin") && pwd.equals ("1")) {return 1;//User 1 else if (name.equals ("admin") && pwd.equals ("2")) {return 2;//User 2} else {return-1;//password error}}/** * Instantiate a chat dress * * @param status/private void getchatserver (int status) {Chatappliaction.chatserver = new chatserver (status);}

4, (client-side code) chatserver Chat Service code logic changes

public class Chatserver {private socket socket; private Handler Handler; private Messagebean Messagebean; private Gson G
son = new Gson ();
The output stream is obtained from the socket object, and the PrintWriter object PrintWriter PrintWriter is constructed.
InputStream input;
OutputStream output;
DataOutputStream DataOutputStream; public chatserver (int status) {initmessage (status); Initchatserver ();}/** * Message Queuing, for passing messages * * @param handler/public VO ID Setchathandler (Handler Handler) {this.handler = Handler;} private void Initchatserver () {//Open thread Receive Message receivemessage ()
;
/** * Initialize User information * * private void initmessage (int status) {Messagebean = new Messagebean ();
Userinfobean Userinfobean = new Userinfobean ();
Userinfobean.setuserid (2);
Messagebean.setmessageid (1);
Messagebean.setchattype (1);
Userinfobean.setusername ("admin");
Userinfobean.setuserpwd ("123123123a");
The following actions mimic when a user clicks on a buddy's expanded chat interface, will save the user ID and chat target user ID if (status = = 1) {//If the user is 1, then he points to the user 2 chat Messagebean.setuserid (1);
Messagebean.setfriendid (2);
else if (status = = 2) {//if user 2, then he points to user 1 chatMessagebean.setuserid (2);
Messagebean.setfriendid (1);
} Chatappliaction.userinfobean = Userinfobean; /** * Send messages * * @param contentmsg/public void SendMessage (String contentmsg) {try {if (socket = = NULL) {message mes
Sage = Handler.obtainmessage ();
Message.what = 1;
Message.obj = "server is closed";
Handler.sendmessage (message);
Return
} byte[] str = contentmsg.getbytes ("Utf-8");//turn content to utf-8 string aaa = new string (str);
Messagebean.setcontent (AAA);
String Messagejson = Gson.tojson (Messagebean); 
/** * Because the server side of the ReadLine () is blocking read * If it does not read the line break or the end of the output stream will always be blocked there * so in the JSON message finally plus line breaks, used to tell the server that the message has been sent * * * * * * * + + ";" Output.write (Messagejson.getbytes ("Utf-8"));//NewLine printing output.flush ();
Refreshes the output stream so that the server immediately receives the string} catch (Exception e) {e.printstacktrace ();
LOG.E ("Test", "Error:" + e.tostring ());  }/** * receives message, in child thread/private void ReceiveMessage () {New Thread (new Runnable () {@Override public void run () {try {//
Shanben 8080 Port issue client request Socket = new Socket (SOCKETURLS.IP, socketurls.port); By the Socket objectThe input stream is obtained and the corresponding BufferedReader object is constructed printwriter = new PrintWriter (Socket.getoutputstream ());
input = Socket.getinputstream ();
Output = Socket.getoutputstream ();
DataOutputStream = new DataOutputStream (Socket.getoutputstream ());
Get information from the client BufferedReader BFF = new BufferedReader (new InputStreamReader (input));
Read Send to server information String line;
while (true) {Thread.Sleep (500);//Get client information while (line = Bff.readline ())!= null) {LOG.I ("socket", "content:" + line);
Messagebean Messagebean = Gson.fromjson (line, messagebean.class);
Message message = Handler.obtainmessage ();
Message.obj = Messagebean.getcontent ();
Message.what = 1;
Handler.sendmessage (message);
} if (socket = = null) break;
Output.close ()//close socket output stream Input.close ()//close socket Input stream Socket.close ()//Close Socket} catch (Exception e) {
E.printstacktrace ();
LOG.E ("Test", "Error:" + e.tostring ());
}}). Start (); Public socket Getsocekt () {if (Socket = = null) return null; return Socket;}}

As a result, code logic has been changed from the logic of message push to the logic of single chat.

This code allows the user 1 and 2 to chat with each other, and the server records their chat record. And the server still has the function of message push.

The above is a small set to introduce Java Socket Chat room programming (ii) the use of socket to achieve a single chat room, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

Related Article

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.