Android Phone socket Communication (server and client) _android

Source: Internet
Author: User
Tags readline

This example for you to share the Android phone socket communication code for your reference, the specific contents are as follows

1, socket communication first to define a good service end of the IP address and port number;

(1). First look at the service-side code:

Package com.example.androidsockettest;
Import Java.io.BufferedReader;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.InputStreamReader;
Import Java.io.OutputStream;
Import Java.net.ServerSocket;

Import Java.net.Socket;
Import Android.net.wifi.WifiInfo;
Import Android.net.wifi.WifiManager;
Import Android.os.Bundle;
Import Android.os.Handler;
Import Android.os.Message;
Import android.app.Activity;
Import Android.content.Context;
Import Android.view.Menu;

Import Android.widget.TextView;
 public class Mainactivity extends activity {public static serversocket serversocket = null;
  public static TextView Mtextview, TextView1;
  Private String IP = "";
 String buffer = ""; public static Handler Mhandler = new Handler () {@Override public void Handlemessage (Android.os.Message msg) {if (msg
  . what==0x11) {Bundle Bundle = Msg.getdata ();
  Mtextview.append ("Client" +bundle.getstring ("msg") + "\ n");
 }
 };

 }; @Override protected void OnCreate (Bundle savedinsTancestate) {super.oncreate (savedinstancestate);
 Setcontentview (R.layout.activity_main);
 Mtextview = (TextView) Findviewbyid (R.ID.TEXTSSS);
 TextView1 = (TextView) Findviewbyid (R.ID.TEXTVIEW1);
 IP = Getlocalip ();
 Textview1.settext ("IP addresss:" +ip);
  New Thread () {public void run () {Bundle Bundle = new Bundle ();
  Bundle.clear ();
  OutputStream output;
  String str = "Communication Success";
   try {serversocket = new ServerSocket (30000);
   while (true) {msg = new message ();
   Msg.what = 0x11;
    try {Socket socket = serversocket.accept ();
    Output = Socket.getoutputstream ();
    Output.write (Str.getbytes ("UTF-8"));
    Output.flush ();
    Socket.shutdownoutput ();
    Mhandler.sendemptymessage (0);
    BufferedReader BFF = new BufferedReader (New InputStreamReader (Socket.getinputstream ()));
    String line = null;
    Buffer = "";
    while (line = Bff.readline ())!=null} {buffer = line + buffer;
    } bundle.putstring ("MSG", buffer.tostring ()); Msg.setData (bundle);
    Mhandler.sendmessage (msg);
    Bff.close ();
    Output.close ();
   Socket.close ();
   catch (IOException e) {e.printstacktrace ();
  '} ' catch (IOException E1) {//TODO auto-generated catch block E1.printstacktrace ();
 }
  };
 }.start ();  
     Private String Getlocalip () {Wifimanager Wifimanager = (wifimanager) getsystemservice (Context.wifi_service);  
     Wifiinfo wifiinfo = Wifimanager.getconnectioninfo ();  
    int ipaddress = wifiinfo.getipaddress (); 
     LOG.D (TAG, "int IP" +ipaddress); 
     if (ipaddress==0) return null; Return ((IPAddress & 0xff) + "." 
        + (Ipaddress>>8 & 0xff) + "." + (ipaddress>>16 & 0xff) + "." 
   + (ipaddress>>24 & 0xff)); 
 } 
 
}

(2). Because it is a mobile phone to do the service side, so at the beginning of the operation of the client is not aware of IP and port number, but the server can be seen after running (pro: You can Test yourself)

2, the client's code

Package com.example.andoroidclient;
Import Java.io.BufferedReader;
Import java.io.IOException;
Import Java.io.InputStreamReader;
Import Java.io.OutputStream;
Import java.net.InetSocketAddress;
Import Java.net.Socket;

Import java.net.SocketTimeoutException;
Import Android.os.Bundle;
Import Android.os.Handler;
Import Android.os.Message;
Import android.app.Activity;
Import Android.view.Menu;
Import Android.view.View;
Import Android.view.View.OnClickListener;
Import Android.widget.Button;
Import Android.widget.EditText;

Import Android.widget.TextView;
 public class Mainactivity extends activity {socket socket = NULL;
 String buffer = "";
 TextView txt1;
 Button send;
 EditText ed1;
 String geted1;
  Public Handler MyHandler = new Handler () {@Override public void Handlemessage (msg) {if (Msg.what = 0x11) {
  Bundle Bundle = Msg.getdata ();
  Txt1.append ("server:" + bundle.getstring ("msg") + "\ n");

 }
 }

 }; @Override protected void OnCreate (Bundle savedinstancestate){super.oncreate (savedinstancestate);
 Setcontentview (R.layout.activity_main);
 Txt1 = (TextView) Findviewbyid (R.ID.TXT1);
 Send = (Button) Findviewbyid (r.id.send);
 ed1 = (edittext) Findviewbyid (r.id.ed1);
 New Mythread ("Establish connection"). Start (); Send.setonclicklistener (New Onclicklistener () {@Override public void OnClick (View v) {geted1 = Ed1.gettext (). toSt
  Ring ();
  Txt1.append ("Client:" + geted1 + "\ n");
  The start thread sends and receives information to the server, new Mythread (geted1). Start ();

 }
 });

 Class Mythread extends Thread {public String txt1;
 Public mythread (String str) {txt1 = str;
  @Override public void Run () {//definition message msg = new messages ();
  Msg.what = 0x11;
  Bundle Bundle = new Bundle ();
  Bundle.clear ();
  try {//Connect the server and set the connection timeout to 5 seconds socket = new socket ();
  Socket.connect (New Inetsocketaddress ("172.20.226.11", 30000), 1000);
  Gets the input output stream outputstream OU = Socket.getoutputstream (); BufferedReader BFF = new BufferedReader (New InputStreamReader (Socket.getinputstream ()));
  Read Send to server info String line = null;
  Buffer = "";
  while (line = Bff.readline ())!= null} {buffer = line + buffer;
  ///Send information to the server Ou.write (txt1.getbytes ("GBK"));
  Ou.flush ();
  Bundle.putstring ("msg", buffer.tostring ());
  Msg.setdata (bundle);
  Sends a message to modify the component Myhandler.sendmessage (msg) in the UI thread;
  Close various input and output streams bff.close ();
  Ou.close ();
  Socket.close (); The catch (sockettimeoutexception aa) {//Connection timeout Displays the message bundle.putstring ("MSG", "Server connection Failure!") in the UI interface.
  Please check that the network is open ");
  Msg.setdata (bundle);
  Sends a message to modify the component Myhandler.sendmessage (msg) in the UI thread;
  catch (IOException e) {e.printstacktrace ();
 }
 }
 }

}

3, finally don't forget to add network permissions

<uses-permission android:name= "Android.permission.INTERNET"/>

SOURCE Download: Http://xiazai.jb51.net/201608/yuanma/android-socket (jb51.net). rar

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.