Creating a socket client in Android (implementing an online chat room)

Source: Internet
Author: User

Here's an example of implementing an Android as a client for a web chat room:

To build an Android client:

<p> </p><p>package Com.example.mysocketclient;</p><p>import Java.io.bufferedreader;import Java.io.bufferedwriter;import Java.io.ioexception;import Java.io.InputStreamReader; Import Java.io.outputstreamwriter;import Java.net.socket;import Java.net.unknownhostexception;import Java.util.date;</p><p>import Android.support.v7.app.actionbaractivity;import Android.support.v7.app.actionbar;import Android.support.v4.app.fragment;import Android.os.AsyncTask;import Android.os.bundle;import Android.view.layoutinflater;import Android.view.menu;import Android.view.MenuItem;import Android.view.view;import Android.view.view.onclicklistener;import Android.view.viewgroup;import Android.widget.button;import Android.widget.edittext;import Android.widget.textview;import android.widget.Toast; Import Android.os.build;</p><p>public class Mainactivity extends Actionbaractivity {</p><p>  private EditText Edit, Edit_content; private TeXtview content; private Button test, send;</p><p>  @Override  protected void OnCreate ( Bundle savedinstancestate) {  super.oncreate (savedinstancestate);   setcontentview ( R.layout.activity_main);   this.edit = (EditText) Super.findviewbyid (r.id.edit);   this.edit_ Content = (EditText) Super.findviewbyid (r.id.edit_content);   this.content = (TextView) Super.findviewbyid ( R.id.show)   this.test = (Button) Super.findviewbyid (r.id.test);   this.send = (Button) Super.findviewbyid (R.id.fasong); </p><p>  this.test.setonclicklistener (new Test ());   this.send.setonclicklistener (new Send ()); </p><p> }</p><p> private class Test implements Onclicklistener {</p><p>   @Override   public void OnClick (View arg0) { </p><p>   connect ();  }</p><p> }</p><p>  priVate class Send implements Onclicklistener {</p><p>   @Override   public void OnClick ( View arg0) {</p><p>   send ();   }</p><p> }</p><p > //----------------------------------------</p><p> socket Socket = null;  BufferedWriter writer = Null; bufferedreader reader = null;</p><p> public void Connect () {</p& gt;<p>    //thread controls Read and write   asynctask<void of current data, String, void> read = new Asynctask<void, String, void> () {</p><p>    @Override    protected void Doinbackground (void ... arg0) {    try {     socket = new socket ( MainActivity.this.edit.getText ()        .tostring (), 12345);      writer = new BufferedWriter (New OutputStreamWriter (&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSp;socket.getoutputstream ()));      reader = new BufferedReader (New InputStreamReader (        socket.getinputstream ()));      Publishprogress ("@success");     } catch (Unknownhostexception E1) {      toast.maketext (Mainactivity.this, "Unable to connect to server! ",        toast.length_short). Show ();      E1.printstacktrace ();     } catch (IOException E1) {      Toast.maketext (Mainactivity.this, "Unable to connect to server! ",        toast.length_short). Show ();      E1.printstacktrace ();     }    try {     string lineString = Null;     while ((lineString = Reader.readline ()) = null) {   & Nbsp;  publishprogress (lineString); &LT;/P&GT;&Lt;p>     }    } catch (IOException e) {      //TODO auto-generated Catch Block     e.printstacktrace ();     }    return null;   }</p><p>    @Override     protected void Onprogressupdate (String ... values) {    if (Values[0].equals ("@ Success ") {     toast.maketext (mainactivity.this," Connect to server! ", Toast.length_short). Show ();     }    </p><p>     content.append ("Others said:" +values[0]);     super.onprogressupdate (values);    }</p><p>  };</p><p>  read.execute ();</p> <p> }</p><p> public void Send () {  try {   content.append (" I said: "+edit_content.gettext (). toString () +"\ n");    writer.write (Edit_content.gettext (). toString () + "\ n");    writer.flush ();    edit_content.settext ("");   } catch (IOException e) {   //TODO Auto-generated catch Block   e.printstacktrace ();   } }</p><p>}</p ><p> </p>


Layout file:

<?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:orientation=" vertical " > <tablelayout android:layout_width= "match_parent" android:layout_height= "Wrap_content" Android                oid:orientation= "Horizontal" > <TableRow> <edittext android:id= "@+id/edit" Android:layout_width= "200DP" android:layout_height= "Wrap_content" android:text= "10.0.2.2"/> <button android:id= "@+id/test" android:layout_width= "Match_pa Rent "android:layout_height=" wrap_content "android:text=" Connection test "/> </tablerow&gt    ; </TableLayout> <textview android:id= "@+id/show" android:layout_width= "Match_parent" Andro Id:layout_height= "Wrap_content"android:text=" "/> <edittext android:id=" @+id/edit_content "android:layout_width=" Match_pa Rent "android:layout_height=" wrap_content "android:hint=" Please enter the chat here "/> <button android:id=" @+id/fasong "android:layout_width=" match_parent "android:layout_height=" wrap_content "android:text=" hair Send Message "/></linearlayout>


First run the server program written on the previous section, and then run the Android client, click the Connect test below:

Run two Android virtual machines as follows:

Online Live chat is possible.

The code is as follows:

http://download.csdn.net/detail/yayun0516/8624193

http://download.csdn.net/detail/yayun0516/8624199

Creating a socket client in Android (implementing an online chat room)

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.