Android Development Chat Room

Source: Internet
Author: User

The purpose of this case is to develop a simple chat room function, all the code is I debug the changes can be used normally, the main function is to use multithreading technology by the server to receive client requests, and then send the chat content to each client Access server. In addition, the login function is realized, and only after the login verification can the chat be realized. Specific technical details in this column does not involve, mainly multithreading based on the socket, the specific code is as follows:

The first is a simple chat model diagram:


The client code is as follows:

feature specifies the IP address and port number of the socket connection, the client is divided into 2 threads A and B, where a thread is responsible for logging on to the connection, the B thread is divided into 2 sub-threads, the first is sending data to the server, and the 2nd is receiving data from the server

public class Mainactivity extends Activity {/** * IP address and port number configuration */private final static String ip_address = "172.21.212.158";p rivate final static int PORT = 12345;/** * control variable */private Button btn_sent,btn_loadon;private EditText Edittext,edit_userna Me,edit_password;private TextView tv_content;private Boolean isconn = false;private Handler Handler = new Handler () {Publi c void Handlemessage (Message msg) {if (Msg.obj.toString (). Contains ("Login succeeded")) {Isconn = true;} Showtoast (msg.what,msg.obj);};    Private clientthread clientthread;private socket socket;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        /** * Initialize control */btn_sent = (Button) Findviewbyid (r.id.btn_sent);        EditText = (editText) Findviewbyid (R.id.edit_text);        Tv_content = (TextView) Findviewbyid (r.id.tv_content);        Btn_loadon = (Button) Findviewbyid (R.id.btn_loadon); Edit_passwoRD = (EditText) Findviewbyid (r.id.edit_password_input);            Edit_username = (EditText) Findviewbyid (r.id.edit_username_input); Btn_loadon.setonclicklistener (New View.onclicklistener () {@Overridepublic void OnClick (View v) {//Get login name and password string user = Edit_username.gettext (). toString (). Trim ();        String pass = Edit_password.gettext (). toString (). Trim ();//Start login thread new Thread (new Connserver (user, pass)). Start ();});        if (socket = = null) {Toast.maketext (Getapplicationcontext (), "null socket", Toast.length_short). Show (); Response Send button Btn_sent.setonclicklistener (new View.onclicklistener () {@Overridepublic void OnClick (View v) {//TODO Auto -generated method stub//The content to be sent as a message, since it is sent to the server new Newclienttask (socket). Execute (Edittext.gettext (). toString ().    Trim () + "\ n"); Edittext.settext ("");}}); public void Showtoast (Int. flag,object msgobj) {switch (flag) {case 0:toast.maketext (this, msgobj.tostring (), Toast. Length_short). Show (); Break;case 1:toast.maketext (This, msgObj.tostring (), Toast.length_short). Show ();d Efault:break;}    /** * * * Connection Server thread */Private class Connserver implements runnable{private String username = null;    Private String password = null;    private int waitTime = 0;    Private Boolean hassendconnmessage = false;    Public Connserver (String user,string pass) {this.username = user;    This.password = pass; }//Create constructor @Overridepublic void Run () {//TODO auto-generated method Stubtry {//Pass data to server socket = new Socket (ip_addre SS, PORT); OutputStream os = Socket.getoutputstream (); byte[] buffer = new BYTE[512]; String str = this.username+ "#" +this.password;buffer = Str.getbytes (); os.write (buffer); hassendconnmessage = true;} catch (Unknownhostexception e) {//Todo auto-generated catch Blocke.printstacktrace ()} catch (IOException e) {//Todo Aut O-generated catch Blocke.printstacktrace ();} InputStream is = null;if (hassendconnmessage) {try {was = Socket.getinputstream (); while (is = = null) {waitTime + = 1000;} Byte[] BUffer2 = new Byte[512];is.read (buffer2); String reuslt = new String (buffer2, "utf-8");//Create a message msg = new Message (); msg.what = 1;msg.obj = Reuslt;handler.send Message (msg); buffer2 = null;} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();}}        if (WaitTime >) {message msg = new Message (); msg.what = 0;msg.obj = "Login timeout"; handler.sendmessage (msg);}} }/** * Client thread class, implements Runnble interface * @author SJM * */Private class Newclienttask extends Asynctask<stri    Ng, Void, string> {private Socket clientscoket;    Public Newclienttask (Socket s) {this.clientscoket = s; } @Overrideprotected void OnPostExecute (String result) {//TODO auto-generated method Stubtv_content.append (result+ "\ n" );} @Overrideprotected string Doinbackground (String ... params) {//TODO auto-generated method stub//receives data from the server string result = Null StringBuilder sb = new StringBuilder (); try {//Send to server OutputStream OS = Clientscoket.getoutputstream (); Os.write (params[0 ]. GetBytes ("Utf-8")); InputStream is = Clientscoket.getinputstream (); byte[] buffer = new Byte[512];is.read (buffer); result = new String (buffer, "utf-8");} catch (Unknownhostexception e) {//TODO auto-generated catch Blocktry {Clientscoket.close ();} catch (IOException E1) {//T ODO auto-generated catch Blocke1.printstacktrace ();} E.printstacktrace ();} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();}        return result;} }}

Next is the function of the server: mainly for verifying logins, and distributing received chat messages, note that the user name and password sent to the server format needs to be customized, here I use User#pass:





Import Java.io.BufferedReader;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.InputStreamReader;
Import Java.io.OutputStream;
Import Java.io.ObjectInputStream.GetField;
Import Java.net.ServerSocket;
Import Java.net.Socket;
Import java.net.SocketException;
Import java.util.ArrayList;
Import Java.util.logging.Handler;


/**
* My server: A message to receive the client and send the message back to each client
* @author SJM
*
*/
public class MyServer {
Set up Socketarray objects to store each socket
public static arraylist<socket> Socketarray = new arraylist<socket> ();
Private final static int PORT = 12345;
private static String USERNAME = "SJM";
private static String passwords = "1234";
private static Socket clientsocket = null;
private static Boolean hasclient = false;
public static void Main (string[] args) {
TODO auto-generated Method Stub
1. Start the service side
try {
ServerSocket Server = new ServerSocket (PORT);
while (true)
{
System.out.println ("Wait for a Connection:");
Clientsocket = Server.accept ();
System.out.println ("received a connection request");
Place the client socket into the Socketarray
Set logon permissions to open a thread when both the user name and password meet the criteria
The implementation method is to open up a thread that validates the login, and then continues to satisfy
New Thread (New Clientpermission (Clientsocket)). Start ();
}
} catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}


/**
* Verify the logged on thread
* @author SJM
*
*/
private static class Clientpermission implements runnable{
private socket socket;
Private String userName = null;//user Name
Private String passwords = null;//password
Public Clientpermission (Socket s) {
This.socket = s;
}
@Override
public void Run () {
TODO auto-generated Method Stub
try {
InputStream is = This.socket.getInputStream ();
byte[] buffer = new BYTE[512];
Is.read (buffer);

String br = new string (buffer);
System.out.println (BR);
The data format of the user name and password is customized when passed in, such as Username#passwords.
if (br! = null) {
String str = br.tostring ();
string[] str2 = Str.split ("#");
UserName = str2[0];
passwords = Str2[1];
System.out.println (str);
Hasclient = Username.contains (userName) &&passwords.contains (Passwords)? True:false;
System.out.println (string.valueof (hasclient));
if (hasclient) {
If the validation is correct
Socketarray.add (socket);
Returns a message
OutputStream OS = Socket.getoutputstream ();
Os.write (New String ("Login succeeded"). GetBytes ("Utf-8"));
buffer = NULL;
Open a thread for the client
New Thread (new Serverthread (socket)). Start ();
}
else{
OutputStream OS = Socket.getoutputstream ();
Os.write (New String ("Password Error"). GetBytes ("Utf-8"));
Is.close ();
Socket.close ();
Socketarray.remove (socket);
return;
}
}
Else
{
OutputStream OS = Socket.getoutputstream ();
Os.write (New String ("Password cannot be empty"). GetBytes ("Utf-8"));
Is.close ();
Socket.close ();
Socketarray.remove (socket);
Return
}
} catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}

}
private static class Serverthread implements runnable{
Private Socket Client_socket;
/**
* Thread Constructors
* @param s
*/
Public Serverthread (Socket s) {
This.client_socket = s;
}
@Override
public void Run () {
TODO auto-generated Method Stub
try {
System.out.println ("Start Up");
while (true)
{
String str = NULL;
byte[] buffer = new BYTE[512];
InputStream is = Client_socket.getinputstream ();
if (is = null) {
Is.read (buffer);
str = new String (buffer, "utf-8");
System.out.println ("received message" +STR);
for (Socket S:socketarray)
{
OutputStream OS = S.getoutputstream ();
Os.write (buffer);
}
}
}
} catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
if (client_socket! = null) {
Socketarray.remove (Client_socket);
}
}
}
}
}

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Android Development Chat Room

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.