Java in the socket communication has been a good example, I just to introduce it into Android, the omission of the inevitable, many places are also worthy of reflection and consideration, master do not have to shoot bricks, can skip this article. Next, demonstrate how Android implements socket communication by knocking at the door.
Server programs
The server program needs to run on the PC, the program is simpler, so there's no need to build an Android project, define a Java class directly, and run the class. It only establishes ServerSocket listening and uses sockets to get the input output stream
The code is as follows |
Copy Code |
Import java.io.IOException; Import Java.io.OutputStream; Import Java.net.ServerSocket; Import Java.net.Socket; public class Simpleserver { /** * @param args * @throws IOException */ public static void Main (string[] args) throws IOException { TODO auto-generated Method Stub Create a ServerSocket to listen for connection requests for client sockets ServerSocket ss=new ServerSocket (30000); The use of loops to accept requests from the client, the server side also corresponds to the production of a socket while (true) { Socket s=ss.accept (); OutputStream Os=s.getoutputstream (); Os.write ("Hello, you have received the New Year's Greetings from the server!" N ". GetBytes (" Utf-8 ")); Os.close (); S.close (); } }} |
Client programs
The code is as follows |
Copy Code |
Package my.learn.tcp; Import Java.io.BufferedReader; Import java.io.IOException; Import Java.io.InputStreamReader; Import Java.net.Socket; Import java.net.UnknownHostException; Import android.app.Activity; Import Android.os.Bundle; Import Android.util.Log; Import Android.widget.EditText; public class SimpleClient extends activity { Private EditText Show; @Override protected void OnCreate (Bundle savedinstancestate) { TODO auto-generated Method Stub Super.oncreate (savedinstancestate); Setcontentview (R.layout.main); Show = (edittext) Findviewbyid (r.id.show); try { Socket socket = new socket ("IP address of your own computer", 30000); 10 seconds after setting is considered a timeout Socket.setsotimeout (10000); BufferedReader br = new BufferedReader (New InputStreamReader ( Socket.getinputstream ())); String line = Br.readline (); Show.settext ("Data from the server:" +line); Br.close (); Socket.close (); catch (Unknownhostexception e) { TODO auto-generated Catch block LOG.E ("Unknownhost", "Data from the server"); E.printstacktrace (); catch (IOException e) { LOG.E ("IOException", "Data from the server"); TODO auto-generated Catch block E.printstacktrace (); } } } |
It should be noted that in the Manifest.xml file, access to the Internet needs to be authorized.
code is as follows |
copy code |
< uses-permission android:name= "Android.permission.INTERNET"/> |