Java Socket Chat Room Programming (i) the use of socket to achieve chat message push _java

Source: Internet
Author: User
Tags flush gettext readline trim

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

There are many examples of using sockets to implement chat online, but I have seen many, many problems exist.

Here I will implement a more complete chat example and explain the logic.

Because this piece of socket is larger, so I will separate a few to write a more complete socket example.

Here we first to implement a simple, server and client communication, implementation of message push function.

Purpose: The server is connected to the client and the client can send a message to the server that the server can push to the client.

1, using Java to establish a socket chat server

1,socketurls determine IP address and port number

public class socketurls{
//IP address public
final static String IP = "192.168.1.110";
Port number public
final static int PORT = 8888;
}

The entrance to the 2,main program

public class Main {public
static void Main (string[] args) throws Exception {
new Chatserver (). Initserver (); 
   }
}

3,bean entity Classes

User Information Userinfobean

public class Main {public

static void Main (string[] args) throws Exception {
new Chatserver (). Initserver ();
}
}

Chat Information Messagebean

public class Messagebean extends Userinfobean {
private long messageid;//message ID
private long groupid;//group ID
PR Ivate Boolean isgoup;//is a group message
private int chattype;//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
//Ellipsis Get/set method
}

4,chatserver Chat Service, the most important program

public class Chatserver {//Socket service private static serversocket server; public Gson Gson = new Gson ();/** * Initialize socket suit Service/public void Initserver () {try {///Create a ServerSocket listener request Server = new ServerSocket (socketurls.port) on port 8080; createm
Essage ();
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 ();
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 () {CreateMessage ()}}).
Start ();
Send information to client outputstream output = Socket.getoutputstream ();
Get information from the client BufferedReader BFF = new BufferedReader (New InputStreamReader (Socket.getinputstream ()));
Scanner Scanner = new Scanner (Socket.getinputstream ()); New Thread (New Runnable () {public void run () {try {String buffer; while (true) {//input from console BufferedReader Strin = new B Ufferedreader (NEW InputStreamReader (system.in));
Buffer = Strin.readline ();
Because the ReadLine is the end point of the line break, add the line to the end of buffer + = "\ n";
Output.write (Buffer.getbytes ("Utf-8"));
Send data Output.flush ();
The catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();}}
). Start ();
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 ());
Gets the information for the client while (line = Bff.readline ())!= null) {Messagebean Messagebean = Gson.fromjson (line, messagebean.class);
System.out.println ("User:" + messagebean.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 ());}}}

2,android End as mobile end connection server

1,appliaction instantiate a global chat Service

public class Chatappliaction extends application {public
static chatserver Chatserver;
public static Userinfobean Userinfobean;
@Override public
void OnCreate () {
super.oncreate ();
}
}

2,IP address and port number are aligned with the server

3, chat strength similar server-side

4,xml layout. Log in, chat

1, Login

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android=
"http://schemas.android.com/apk/" Res/android "
android:layout_width=" match_parent "
android:layout_height=" match_parent "
android:o" rientation= "vertical" >
<edittext
android:id= "@+id/chat_name_text"
Match_parent "
android:layout_height=" wrap_content "
android:hint=" username "
android:text=" admin "/>
<edittext
android:id= "@+id/chat_pwd_text"
android:layout_width= "Match_parent"
android: layout_height= "Wrap_content"
android:hint= "password"
android:text= "123123123a"
android:inputtype= " Numberpassword "/>
<button
android:id=" @+id/chat_login_btn "android:layout_width=" Match_
Parent "
android:layout_height=" wrap_content "
android:hint=" login "/>
</LinearLayout>

2, chatting

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android= "http://schemas.android.com/apk/res/" Android "xmlns:tools=" Http://schemas.android.com/tools "android:layout_width=" Match_parent "android:layout_height = "Match_parent" android:orientation= "vertical" tools:context= ". Activity. Mainactivity "> <scrollview android:id=" @+id/scrollview "android:layout_width=" Match_parent "Android:layout_" height= "0DP" android:layout_weight= "0.9" > <linearlayout android:id= "@+id/chat_ly" Match_parent "android:layout_height=" match_parent "android:orientation=" vertical "> </LinearLayout> </ scrollview> <linearlayout android:layout_width= "match_parent" android:layout_height= "Wrap_content" Android:o rientation= "Horizontal" > <edittext android:id= "@+id/chat_et" android:layout_width= "0DP" Android:layout_ height= "Match_parent" android:layout_weight= "0.8"/> <button android:id= "@+id/send_btn" android:layout_width= "0DP" android:layout_height="Match_parent" android:layout_weight= "0.2" android:text= "send"/> </LinearLayout> </LinearLayout> 

5,loginactivity login

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) {if GetLogin (chat
_name_text.gettext (). ToString (). Trim (), Chat_pwd_text.gettext (). ToString (). Trim ()) {getchatserver ();
Intent Intent = new Intent (loginactivity.this, Mainactivity.class);
StartActivity (Intent);
Finish ();
}
}
}); Private Boolean GetLogin (string name, string pwd) {if textutils.isempty (name) | |
Textutils.isempty (PWD)) return false;
if (name.equals ("admin") && pwd.equals ("123123123a")) return true; return FALSe private void Getchatserver () {chatappliaction.chatserver = new Chatserver ();}}

6,mainactivity chat

public class Mainactivity extends Appcompatactivity {private linearlayout chat_ly, private TextView Left_text, Right_vie
W
Private EditText Chat_et;
Private Button send_btn; Private Viewgroup.layoutparams layoutparams = new Viewgroup.layoutparams (ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT); @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (
R.layout.activity_main);
Chat_ly = (linearlayout) Findviewbyid (R.id.chat_ly);
Chat_et = (edittext) Findviewbyid (R.id.chat_et);
SEND_BTN = (Button) Findviewbyid (R.ID.SEND_BTN);
Send_btn.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) {
ChatAppliaction.chatServer.sendMessage (Chat_et.gettext (). toString (). Trim ());
Chat_ly.addview (Initrightview (Chat_et.gettext (). toString (). Trim ()));
}
});
Add message Receive Queue ChatAppliaction.chatServer.setChatHandler (new Handler () {@Override public void Handlemessage (msg) { if (Msg.what = 1{///Send back message, update UI Chat_ly.addview (Initleftview (msg.obj.toString ()));}
}); /** the right message * @param messagecontent * @return/private View Initrightview (String messagecontent) {Right_view = new TEXTV
Iew (this);
Right_view.setlayoutparams (Layoutparams);
Right_view.setgravity (View.focus_right);
Right_view.settext (messagecontent);
return right_view; /** Left message * @param messagecontent * @return/private View Initleftview (String messagecontent) {left_text = new Textvie
W (this);
Left_text.setlayoutparams (Layoutparams);
Left_text.setgravity (View.focus_left);
Left_text.settext (messagecontent);
return left_text; }
}

7,chatserver chat logic, most important

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 () {initmessage (); Initchatserver ();}/** * Message Queuing, for passing messages * * @param handler/public void Setchathandle R (Handler Handler) {this.handler = Handler;} private void Initchatserver () {//Open thread receives message receivemessage ();}/** * Initialize user letter 
interest/private void Initmessage () {Messagebean = new Messagebean (); Messagebean.setuserid (1); Messagebean.setmessageid (1);
Messagebean.setchattype (1);
Messagebean.setusername ("admin");
Chatappliaction.userinfobean = Messagebean; /** * 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);
The input stream is obtained from the socket object 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);
Gets the information for the client while (line = Bff.readline ())!= null) {LOG.I ("socket", "content:" + line);
Message message = Handler.obtainmessage ();
Message.obj = line;
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 (); }
}

Written here, all the code has been completed.

This demo can realize the mobile phone to send messages to the server, the server to the phone to send messages.

This demo can be considered a push function, but the real push is not so simple. As an introduction to a socket to understand, you can see the idea of socket programming.

The above is a small set to introduce Java Socket Chat room programming (a) the use of socket to achieve chat message push, 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!

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.