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