The Android Socket client

Source: Internet
Author: User

Receive data do not use ReadLine (), with Read ()

Socket msocket = new socket ("192.168.1.100", 8888);

DataInputStream dinput = new DataInputStream (Msocket.getinputstream ())

Read the data sent from the service side:

int length = Dinput.read (BBUF);
String mstrmsg = new String (bbuf, 0, length, "gb2312");

Package Com.example.tcp_client;import Java.io.datainputstream;import java.io.printwriter;import Java.net.socket;import Android.annotation.suppresslint;import Android.os.handler;import Android.os.Message;import Android.os.strictmode;import Android.util.Log; @SuppressLint ("Newapi") Public classTCPClient implements runnable{Private StaticFinal String ServerIP ="192.168.1.100"; Private StaticFinalintServerPort =8888; PrivateThread Mthread =NULL; Private StaticSocket Msocket =NULL; PrivateDataInputStream Dinput; Private StaticPrintWriter Mprintwriter =NULL; Private StaticString mstrmsg =""; Private StaticString TAG ="TCPClient"; //receive line Cheng send over information and display it with TextView     PublicHandler Mhandler =NewHandler () { Public voidhandlemessage (Message msg) {super.handlemessage (msg); LOG.E ("server says:", mstrmsg); Mainactivity.appendtext ("server says:"+mstrmsg);    }    };  Public  voidstarttcpclient () {Strictmode.setthreadpolicy (NewStrictMode.ThreadPolicy.Builder (). Detectdiskreads (). Detectdiskwrites (). Detectnetwork (). Penaltylog (). Build        ()); Strictmode.setvmpolicy (NewStrictMode.VmPolicy.Builder (). Detectleakedsqlliteobjects (). Detectleakedclosableobjects (). Penaltylog ().        Penaltydeath (). build ()); Try        {            //①socket Instantiation, connecting to the serverMsocket =NewSocket (ServerIP, ServerPort); //② Get socket input/output stream for read and write operationsdinput=NewDataInputStream (Msocket.getinputstream ()); Mprintwriter=NewPrintWriter (Msocket.getoutputstream (),true); NewThread (TCPClient. This). Start (); } Catch(Exception e) {log.e (TAG, e.tostring ()); }   }       Public Static voidsendtoserver (String sendmsg) {mprintwriter.print (sendmsg);   Mprintwriter.flush (); }      /** * Read the information sent from the server and send it to the UI thread via handler*/    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(Exception e) {e.printstacktrace (); }   }}
TCP Service Side

Using instantiation can

Try
{
TcpClient =new tcpclient ();
TcpClient. Starttcpclient ();
} catch (Exception e)
{
Todo:handle exception
LOG.E ("Mainactivity", e.tostring ());
}

The Android Socket client

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.