Android Socket Server

Source: Internet
Author: User

The first is to ensure that the server is connected to the client, Ping does not connect.

TCP Server-side code

Package Com.example.tcp_server;import Java.io.datainputstream;import java.io.ioexception;import Java.io.printwriter;import Java.net.serversocket;import Java.net.socket;import Java.util.ArrayList;import Java.util.list;import Java.util.concurrent.executorservice;import Java.util.concurrent.executors;import Android.annotation.suppresslint;import Android.os.handler;import Android.os.message;import Android.os.StrictMode; Import Android.util.Log; @SuppressLint ("Newapi") Public classTcpservice implements runnable{//Server Port    Private StaticFinalintServerPort =2001; //Store all client socket connection Objects    Private StaticList<socket> mclientlist =NewArraylist<socket>(); //thread Pool    PrivateExecutorservice Mexecutorservice; //ServerSocket Object    PrivateServerSocket Mserversocket; Private StaticPrintWriter Mprintwriter; Private StaticString mstrmsg;  PublicTcpservice () {Try{strictmode.setthreadpolicy (NewStrictMode.ThreadPolicy.Builder (). Detectdiskreads (). Detectdiskwrites (). Detectnetwork (). Penaltylog (). Build (            )); Strictmode.setvmpolicy (NewStrictMode.VmPolicy.Builder (). Detectleakedsqlliteobjects (). Detectleakedclosableobjects (). Penaltylog ().            Penaltydeath (). build ()); //setting up server portsMserversocket =NewServerSocket (ServerPort); //Create a pool of threadsMexecutorservice =Executors.newcachedthreadpool (); LOG.E ("Tcpservice","start ..."); //the socket object used to temporarily save the client connection            NewThread (Tcpservice. This). Start (); }        Catch(IOException e) {LOG.E ("Tcpservice", e.tostring ());        E.printstacktrace (); }    }    //receive line Cheng send over information and display it with TextView     Public StaticHandler Mhandler =NewHandler () { Public voidhandlemessage (Message msg) {super.handlemessage (msg); LOG.E ("server says:", mstrmsg); Mainactivity.appendtext ("server says:"+mstrmsg);     }    }; //Each client opens a single thread    Static classThreadserver implements Runnable {PrivateSocket Msocket; PrivateDataInputStream Dinput;  Publicthreadserver (socket socket) throws IOException { This. Msocket =socket; Dinput=NewDataInputStream (Socket.getinputstream ()); Sendtoclient ("hello,tcp Server ..."); }         Public voidrun () {Try            {                byte[] Bbuf =New byte[10000];  while(true) {                                        if(!msocket.isclosed ()) {                        if(msocket.isconnected ()) {if(!Msocket.isinputshutdown ()) {                                intLength =Dinput.read (BBUF); Mstrmsg=NewString (Bbuf,0, Length,"gb2312"); Mstrmsg+="\ n";                            Mhandler.sendmessage (Mhandler.obtainmessage ()); }                        }                    }                }            }            Catch(IOException e) {e.printstacktrace (); }        }    }     Public Static  voidsendtoclient (String msg) {Try{             for(Socket client:mclientlist) {mprintwriter=NewPrintWriter (Client.getoutputstream (),true);            MPRINTWRITER.PRINTLN (msg); }        }        Catch(Exception e) {LOG.E ("sending a message to the client failed", e.tostring ()); }    }     Public voidrun () {Try{Socket Client=NULL;  while(true) {LOG.E ("Tcpservice","Receiving customer Connections"); //receive client connections and add to listClient =mserversocket.accept ();                Mclientlist.add (client); //open a client threadMexecutorservice.execute (Newthreadserver (client)); }        }        Catch(Exception e) {LOG.E ("Listening Client", e.tostring ()); }    }}
Tcpservice

Front

<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"Android:layout_width="fill_parent"Android:layout_height="fill_parent"android:orientation="Vertical"> <EditText Android:id="@+id/myinternet_tcpclient_edittext01"Android:layout_width="fill_parent"Android:layout_height="200px"Android:text="Chat history: \ n"> </EditText> <EditText Android:id="@+id/myinternet_tcpclient_edittext02"Android:layout_width="fill_parent"Android:layout_height="wrap_content"Android:text="Enter the content you want to send"> </EditText> <LinearLayout android:layout_width="fill_parent"Android:layout_height="wrap_content"android:orientation="Horizontal"android:gravity="Center"> <Button Android:id="@+id/myinternet_tcpclient_btnsend"Android:layout_width="400px"Android:layout_height="wrap_content"Android:text="Send"/> </LinearLayout> </LinearLayout>

Background

Package Com.example.tcp_server;import android.os.bundle;import android.app.activity;import android.util.Log; Import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.button;import Android.widget.EditText; Public classMainactivity extends Activity {//declaring Objects    PrivateButton Msendbutton; Private StaticEditText mEditText01; Private StaticEditText mEditText02; Private StaticString TAG ="shit="; @Overrideprotected voidonCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main); //Start the server        NewTcpservice (); Msendbutton=(Button) Findviewbyid (r.id.myinternet_tcpclient_btnsend); mEditText01=(EditText) Findviewbyid (r.id.myinternet_tcpclient_edittext01); mEditText02=(EditText) Findviewbyid (r.id.myinternet_tcpclient_edittext02); //send a button to register an eventMsendbutton.setonclicklistener (NewOnclicklistener () { Public voidOnClick (View v) {Try                {                    //Get what we entered in the edit boxString str = Medittext02.gettext (). toString () +"\ n"; Medittext01.append ("I said:"+str); //sending messages to clientsTcpservice.                                    Sendtoclient (str); } Catch(Exception e) {log.e (TAG, e.tostring ());    }            }        }); }     Public Static voidAppendText (String msg) {medittext01.append (msg); }}
mainactivity

Android Socket Server

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.