1. Implement Server
Import java. io. IOException; import java. io. outputStream; import java.net. serverSocket; import java.net. socket; public class myService {public myService () {try {// ServerSocket object is used to listen for Socket connections from the client. If no connection is established, the object remains in the waiting state. 30000 is the port number ServerSocket s = new ServerSocket (30000); // permanent loop, so that the server can accept the client request at any time while (true) {// obtain the client Socket // If a client Socket connection request is received, this method returns a Socket so = s corresponding to the client Socket. accept (); // obtain the output stream OutputStream I = so. getOutputStream (); String msg = "hello! "; // Write string I. write (msg. getBytes (); // close the input stream I. close (); // close the client connection so. close () ;}} catch (IOException e) {e. printStackTrace () ;}/ *** @ param args */public static void main (String [] args) {new myService ();}}
2. Implement the client
Import java. io. bufferedReader; import java. io. IOException; import java. io. inputStreamReader; import java.net. socket; import java.net. unknownHostException; import android. OS. bundle; import android. app. activity; import android. util. log; import android. widget. textView; public class MainActivity extends Activity {private TextView t; private static String s; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); t=(textview%this.findviewbyid(r.id.txt); // you need to create a subthread. network operations cannot run new Thread () {public void run () {Socket so; try {// use the IP address of your computer and establish the client Socket so = new Socket ("222.201.165.95", 30000) with the port number; // use the application Socket to create a BufferedReader object, used to receive data from Socket Stream BufferedReader br = new BufferedReader (new InputStreamReader (so. getInputStream (); s = br. readLine (); Log. v ("re", s); t. setText (s); br. close (); so. close ();} catch (UnknownHostException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace ();}}}. start ();}}
3. Must be declared in the manifest File
<uses-permission android:name="android.permission.INTERNET"/>
When running, run the server program before running the client program.
This article is from the "7603943" blog, please be sure to keep this source http://7613943.blog.51cto.com/7603943/1287617