This article describes the implementation of the Android programming TCP, UDP client communications. Share to everyone for your reference, specific as follows:
In the process of Android development, inevitably, to develop TCP/UDP communication program, the following two pieces of code, respectively, introduced the TCP/UCP through an example:
Code One TCP communication:
private void Tcpdata () {try {socket s = new socket ("192.168.0.25", 65500);
Outgoing stream redirect to socket outputstream out = S.getoutputstream ();
Note that the second parameter is true automatically flush, otherwise you need to manually manipulate Out.flush () printwriter output = new PrintWriter (out, true); Output.println ("Hello ideasandroid!
Pseudo IP is: "+ Simcardtoip (" 13512345006 "));
InputStream 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 process of UDP communication:
public string send (String msg) {StringBuilder sb = new StringBuilder ();
InetAddress local = null; try {local = Inetaddress.getbyname ("192.168.0.25");//native test catch (unknownhostexception e) {E.prin
Tstacktrace ();
try {dsocket = new datagramsocket ();//Note that this is the first place to set permissions in the configuration file, or it will throw out the less privileged exception} 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 (); }
For more information on Android-related content readers can view the site topics: "The Android Communication method Summary", "Android Development introduction and Advanced Course", "Android debugging techniques and common problems solution summary", "Android Multimedia operating skills Summary (audio, Video, audio, etc.), "Summary of Android Basic components usage", "Android View Overview", "Android Layout layout skills Summary" and "Android Control usage Summary"
I hope this article will help you with the Android program.