Android Network Programming Socket

Source: Internet
Author: User

1. Server-Side development

Create a Java program

public class MyServer {//definition saves all sockets, establishes a connection with the client to get a socketpublic static list<socket> socketlist = new ArrayList <Socket> ();p ublic static void Main (string[] args) throws IOException {ServerSocket server = new ServerSocket (8888); while (true) {System.out.println ("Start listening port 8888"); Socket socket = server.accept (); SYSTEM.OUT.PRINTLN ("Connect succeed.");   Socketlist.add (socket);//each time a client connects, a Serverthread thread is started for the Client Service new thread (new myserverrunnable (socket)). Start (); }}public Static class Myserverrunnable implements Runnable {//defines the current thread processing socketsocket socket = null;//The input for the socket processed by the thread Stream BufferedReader BufferedReader = null;public myserverrunnable (socket socket) {This.socket = socket;try {// Place data from the server-side input stream into the read buffer BufferedReader = new BufferedReader (New InputStreamReader (Socket.getinputstream ()));} catch (Exception e) {e.printstacktrace ();}} @Overridepublic void Run () {String content = null;//uses the loop to read the data sent by the client from the socket while (content = Readfromclient ())! = nul L) {//Traverse SOCEach socket in the ketlist, sends the read content to each socket once for (socket socket:MyServer.socketList) {OutputStream Outputstream;try { OutputStream = Socket.getoutputstream (); Outputstream.write (("Server:" + content + "\ n"). GetBytes ("Utf-8");} catch (IOException e) {e.printstacktrace ();}}}} Defines the read client information public String readfromclient () {try {return bufferedreader.readline ();} catch (Exception e) { E.printstacktrace ();} return null;}}}

2. Create an Android program

1) Layout

<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:gravity= "center"    android:orientation= "vertical"    tools:context= ". Mainactivity ">    <textview        android:id=" @+id/show "        android:layout_width=" Wrap_content        " android:layout_height= "Wrap_content"        android:text= "show received server-side data"/>    <button android:id=        "@+ Id/send "        android:layout_width=" match_parent "        android:layout_height=" wrap_content "        android:text= "Send data to server side"/></linearlayout>

2) Clientthread class

Package Com.example.testclient;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.handler;import Android.os.looper;import Android.os.message;import Android.util.log;public class Clientthread implements Runnable {private Socket s;// Defines the handler object that sends a message to the UI thread handler handler;//defines the handler object that receives the UI thread handler revhandler;//the thread handles the input and output stream used by the socket BufferedReader BR = Null;outputstream OS = null;public clientthread (Handler Handler) {this.handler = Handler;} @Overridepublic void Run () {s = new Socket (); LOG.D ("111111111111", ""); try {//192.168.0.26 is the PC IP address.

S.connect (New Inetsocketaddress ("192.168.0.26", 8888), 5000); LOG.D ("111111111111", "$$"); br = new BufferedReader (new InputStreamReader, S.getinputstream ()); OS = S.getoutputstream ();//Start a child thread to read the server corresponding data new Thread () {@Overridepublic void run () {String content = null;//continuously reads the contents of the socket input stream try {while (c Ontent = Br.readline ()) = null) {//each time the data from the server is read, the sent message notifier//interface displays the data message msg = new Message (); msg.what = 0X123;MSG.O BJ = Content;handler.sendmessage (msg); LOG.D ("111111111111", content);}} catch (IOException io) {io.printstacktrace ();}}}. Start ();//Initialize Looperlooper.prepare () for current thread,//Create Revhandler Object revhandler = new Handler () {@Overridepublic void Handlemessage (Message msg) {//receives the user input data in the UI thread if (msg.what = = 0x345) {//writes the user's input in the text box to the network try {os.write ("Client" + MSG.O Bj.tostring () + "\ r \ n"). GetBytes ("Utf-8");} catch (Exception e) {e.printstacktrace ();}}}};/ /start Looperlooper.loop ();} catch (sockettimeoutexception e) {message msg = new Message (); msg.what = 0x123;msg.obj = "Network connection timed out!" "; Handler.sEndmessage (msg);} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();}}}

 3. Mainactivity

public class Mainactivity extends Activity {Handler handler;//defines the sub-thread Clientthread clientthread that communicates with the server; TextView Show; Button send, @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main); show = (TextView) This.findviewbyid (r.id.show); send = (Button) This.findviewbyid (R.id.send); Send.setonclicklistener (new View.onclicklistener () {@Overridepublic void OnClick (View ARG0) {//TODO auto-generated method Stubtry {//When the user presses the button, encapsulates the data entered by the user into message//and then sends it to the child thread handlermessage msg = new Message () ; msg.what = 0x345;msg.obj = "Android Network programming--socket communication Programming"; ClientThread.revHandler.sendMessage (msg);} catch (Exception e) {e.printstacktrace ();}}}); Handler = new Handler () {@Overridepublic void handlemessage (Message msg) {//If the message comes from a child thread if (msg.what = = 0x123) {//reads the content appended Show.append ("\ n" + msg.obj.toString ()) in the text box; show.settextsize (50);}}; Clientthread = new Clientthread (handler);//client initiates Clientthread thread creates a network connection, reads data from the server new thread (Clientthread). Start ();}} 

Reference: http://blog.csdn.net/thanksgining/article/details/43561053

Android Network Programming Socket

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.