Android simple c/S chat communication function based on socket implementation _android

Source: Internet
Author: User
Tags flush readline sendmsg

This article describes the Android based on socket implementation of simple C/S chat communication function. Share to everyone for your reference, specific as follows:

Main idea: Send a message on the client, open a thread in the background to act as the service side, receive the message immediately feedback to the client.

Step one: Create a socketclientactity class that continues the activity, wrapped as com.pku.net

Write the layout file Socketclient.xml, code as follows:

<?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" >
  <scrollview
    android:id= "@+id/scrollview3" android:layout_width= "Fill_"
    Parent "
    android:layout_height=" wrap_content ">
    <textview
      android:id=" @+id/chattxt2
      " Android:layout_width= "Fill_parent"
      android:layout_height= "wrap_content"
      android:background= "#98F5FF" />
  </ScrollView>
  <edittext
    android:id= "@+id/chattxt"
    android:layout_width= " Fill_parent "
    android:layout_height=" wrap_content "/>
  <button android:id=" @+id/chatok "
    android:layout_width= "wrap_content"
    android:layout_height= "wrap_content"
    android:text= "Send" >
  </Button>
</LinearLayout>

Next, write the Socketclientactity.java file:

Package com.pku.net;
Import Java.io.BufferedReader;
Import Java.io.BufferedWriter;
Import java.io.IOException;
Import java.net.UnknownHostException;
Import Java.io.InputStreamReader;
Import Java.io.OutputStreamWriter;
Import Java.net.Socket;
Import android.app.Activity;
Import Android.os.Bundle;
Import Android.view.View;
Import android.widget.*;
  public class Socketclientactivity extends activity {socketserverthread yaochatserver; /** called the activity is a.
    * * @Override public void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
    Setcontentview (r.layout.socketclient);
    try {yaochatserver = new socketserverthread ();
    catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();
    } if (Yaochatserver!= null) {Yaochatserver.start ();
    } findviews ();
  Setonclick ();
  Private EditText Chattxt;
  Private TextView chattxt2;
  Private Button Chatok; Public VoiD findviews () {chattxt = (edittext) This.findviewbyid (r.id.chattxt);
    Chattxt2 = (TextView) This.findviewbyid (R.ID.CHATTXT2);
  Chatok = (Button) This.findviewbyid (R.id.chatok); private void Setonclick () {Chatok.setonclicklistener (new View.onclicklistener () {@Override public vo
        ID OnClick (View v) {try {connecttoserver (Chattxt.gettext (). toString ());
        catch (Unknownhostexception e) {//TODO auto-generated catch block E.printstacktrace ();
        catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();
  }
      }
    }); public void Connecttoserver (String socketdata) throws Unknownhostexception, IOException {socket socket = Re
    Questsocket ("127.0.0.1", 5000);
    SENDMSG (socket, socketdata);
    String txt = receivemsg (socket);
  This.chattxt2.setText (TXT); Private Socket Requestsocket (String host, int port) throws UnknownhosteXception, IOException {socket socket = new socket (host, port);
  return socket; } private void sendmsg (socket socket, String msg) throws IOException {BufferedWriter writer = new BufferedWriter (NE
    W OutputStreamWriter (Socket.getoutputstream ()));
    Writer.write (Msg.replace ("\ n", "") + "\ n");
  Writer.flush (); Private String receivemsg (socket socket) throws IOException {BufferedReader reader = new BufferedReader (New Input
    StreamReader (Socket.getinputstream ()));
    String txt = reader.readline ();
  return txt;

 }
}

Write Androidmanifest.xml file:

<?xml version= "1.0" encoding= "Utf-8"?> <manifest xmlns:android= "http://schemas.android.com/apk/res/" Android "package=" Com.pku.net "android:versioncode=" 1 "android:versionname=" 1.0 "> <uses-sdk android:minsdkv ersion= "8"/> <uses-permission android:name= "Android.permission.INTERNET"/> <application android:icon= "@drawable/ic_launcher" android:label= @string/app_name "> <activity android:name=". Httpurlactivity "android:label=" @string/app_name "> <intent-filter> <action android:name=" Android.intent.action.MAIN "/> <category android:name=" Android.intent.category.LAUNCHER "/> </in tent-filter> </activity> <activity android:name= "Getnetimage" ></activity> <activity an Droid:name= "httpclientactivity" ></activity> <activity android:name= "Socketclientactivity" ></

 Activity> </application> </manifest>

Finally, the file Socketserverthread.java for the backend server is written as follows:

Package com.pku.net;
Import Java.io.BufferedReader;
Import Java.io.BufferedWriter;
Import java.io.IOException;
Import Java.io.InputStreamReader;
Import Java.io.OutputStreamWriter;
Import Java.net.ServerSocket;
Import Java.net.Socket;
    public class Socketserverthread extends Thread {public socketserverthread () throws IOException {Createsocket ();
    Create a socket server} public void run () {socket client;
    String txt;
        try {while (true)/thread infinite loop, real-time listening socket port {client = Responsesocket ();
        Respond to client link requests ...
          while (true) {txt = receivemsg (client);
          SYSTEM.OUT.PRINTLN (TXT);
          The link obtains the client sends the message, and displays it on the server side screen sendmsg (client, TXT);
          Returns a message to the client if (true) break;
        Interrupt, continue waiting for link request} closesocket (client);
    Close this link} catch (IOException e) {System.out.println (e);
  } private ServerSocket server = null; Private statIC final int PORT = 5000;
  Private BufferedWriter writer;
  Private BufferedReader reader;
    private void Createsocket () throws IOException {server = new ServerSocket (PORT, 100);
  System.out.println ("Server starting..");
    Private socket Responsesocket () throws IOException {Socket client = server.accept ();
    SYSTEM.OUT.PRINTLN ("Client connected.");
  return client;
    private void closesocket (socket socket) throws IOException {reader.close ();
    Writer.close ();
    Socket.close ();
  SYSTEM.OUT.PRINTLN ("client closed."); } private void sendmsg (socket socket, String MSG) throws IOException {writer = new BufferedWriter (New OUTPUTSTREAMW
    Riter (Socket.getoutputstream ()));
    Writer.write (MSG + "\ n");
  Writer.flush ();
        Private String receivemsg (socket socket) throws IOException {reader = new BufferedReader (New InputStreamReader (
    Socket.getinputstream ())); SYSTEM.OUT.PRINTLN ("Server get input from client socket ...");
    String txt = "Sever send:" + reader.readline ();
  return txt; }/* public static void Main (final String args[]) throws IOException {Socketserverthread yaochatserver = new Socke
    Tserverthread ();
    if (yaochatserver!= null) {Yaochatserver.start ();

 }
  }  */
}

The results of the operation are shown below:

For more information on Android-related content readers can view the site topics: "The Android Communication method Summary", "Android Development introduction and Advanced Course", "Android debugging techniques and common problems solution summary", "Android Multimedia operating skills Summary (audio, Video, audio, etc.), "Summary of Android Basic components usage", "Android View Overview", "Android Layout layout skills Summary" and "Android Control usage Summary"

I hope this article will help you with the Android program.

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.