In the process of Android development, it is inevitable to develop TCP/UDP CommunicationProgram, The following two sectionsCodeDescribes an instance of TCP/UCP:
Code 1:
Private void tcpdata (){
Try {
Socket S = new socket ("192.168.0.25", 65500 );
// Outgoing stream redirect to socket
Outputstream out = S. getoutputstream ();
// Note that if the second parameter is set to true, it will be automatically flush; otherwise, you need to manually operate out. Flush ()
Printwriter output = new printwriter (Out, true );
Output. println ("Hello ideasandroid! The pseudo IP address is :"
+ Simcardtoip ("13512345006 "));
Inputstream = S. getinputstream ();
Datainputstream input = new datainputstream (inputstream );
Byte [] B = new byte [10000];
Int length = input. Read (B );
Inputreader = new inputstreamreader (inputstream );
String MSG = new string (B, 0, length, "gb2312 ");
Toast. maketext (tcptest. This, MSG, 1000). Show ();
Log. D ("TCP Demo", "Message from server:" + MSG );
S. Close ();
} Catch (unknownhostexception e ){
E. printstacktrace ();
} Catch (ioexception e ){
E. printstacktrace ();
}
}
The following code is the UDP communication process: Public String send (string MSG ){ Stringbuilder sb = new stringbuilder (); Inetaddress local = NULL; Try { Local = inetaddress. getbyname ("192.168.0.25"); // local test } Catch (unknownhostexception e ){ E. printstacktrace (); } Try { Dsocket = new datagramsocket (); // note that you must set the permission in the configuration file first. Otherwise, an exception occurs. } Catch (socketexception e ){ E. printstacktrace (); } Int msg_len = MSG = NULL? 0: MSG. Length (); Datagrampacket dpacket = new datagrampacket (msg. getbytes (), msg_len, Local, server_port ); Try { Dsocket. Send (dpacket ); } Catch (ioexception e ){ E. printstacktrace (); } Try { Dsocket. Receive (dpacket ); SB. append (new string (dpacket. getdata ())); } Catch (ioexception e ){ // Todo auto-generated Catch Block E. printstacktrace (); } Dsocket. Close (); Return sb. tostring (); }