Summary of Socket communication in Android Network Programming
Create a server:
1. Specify a port to instantiate a ServerSocket
2. Call the accept method of ServerSocket to wait for blocking during connection.
3. Obtain the underlying Socket stream for read/write operations.
4. encapsulate data into a stream
5. Read and Write the Socket
6. Close the stream.
To create a client:
1. instantiate the Socket through the IP address and port and request to connect to the server
2. Obtain the underlying Socket stream for read/write operations.
3. encapsulate data into an instance of a stream (BufferedReader/PrintWriter, DataOutputStream/DataInputStream)
4. Read and Write the Socket
5. Close the stream.
Use ServerSocket to create a server:
Public static void main (String [] args) throws IOException {// TODO Auto-generated method stub // create a ServerSo viewing feature, used to listen to the client Socket connection request ServerSocket ss = new ServerSocket (3000); while (true) {// each time the client Socket request is received, the server also generates a Socket, wait until the request is received .. Socket s = ss. accept (); OutputStream OS = s. getOutputStream (); // The Socket generated by the server side to obtain the output stream OS. write ("Hello, you have received a blessing from the server! \ N ". getBytes (); OS. close (); s. close ();}}
The client uses Socket for communication:
The test environment is a PC-side server. When the mobile phone is a client, the PC and the mobile phone need to connect to the same LAN. The PC and the mobile phone are in the same network segment.
Package com. example. simpleclient; 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. view. menu; import android. view. menuItem; import android. widget. textView; public class MainActivity extends Activity {TextView text; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); text = (TextView) findViewById (R. id. text); new Thread () {@ Overridepublic void run () {// TODO Auto-generated method stubtry {// create a Socket to connect to the remote server, the Ip address is the IP address of the server PC, and the test environment is the PC server. When the mobile phone is a client, the PC and the mobile phone need to connect to the same LAN, the PC and mobile phone are in the same CIDR Block Socket = new socket ("192.168.88", 3000); // set the input stream package scale BufferedReaderBufferedReader br = new BufferedReader (new InputStreamReader (Socket. getInputStream (); String line = br. readLine (); text. setText ("data from the service:" + line); br. close (); socket. close ();} catch (UnknownHostException e) {// TODO Auto-generated catch blocke. printStackTrace ();} catch (IOException e) {// TODO Auto-generated catch blocke. printStackTrace ();}}}. start ();}}
The problem of input and output streams on the client and server is confusing:
On the client:
Socket. getInputStream (); reads data from the server from the socket
Socket. getOutputStream (); writes data to the socket and transmits the data to the server. The server reads the data in the input stream of its socket.
On the server side:
Socket. getInputStream (); read data from the client from the socket
Socket. getOutputStream (); writes data to the socket and sends it to the client. The client reads the data in the input stream of its socket.
That is to say, the input and output streams on the client and the server correspond,
Connect the input stream to the output stream
Input/output stream packaging:
Method 1: binary data stream
DataInputStream in = new DataInputStream (socket. getInputStream (); // receives the client information DataOutputStream out = new DataOutputStream (socket. getOutputStream (); // sends a message to the client
Method 2:
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
SocketClient, java
Import java. io. bufferedReader; import java. io. bufferedWriter; import java. io. dataInputStream; import java. io. dataOutputStream; import java. io. inputStreamReader; import java. io. outputStreamWriter; import java. io. printWriter; import java.net. socket; import android. app. activity; import android. OS. bundle; import android. view. view; import android. widget. button; import android. widget. editText; import android. widget. T ExtView; public class socketClient extends Activity {private Button button; private TextView text; private EditText edit;/** Called when the activity is first created. * // @ Overridepublic void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); button = (Button) findViewById (R. id. button); edit = (EditText) findViewById (R. id. edit); text = (TextView) findVi EwById (R. id. text); button. setOnClickListener (new View. onClickListener () {private Socket socket = null; @ Overridepublic void onClick (View v) {// TODO Auto-generated method stubString sendMsg = edit. getText (). toString () + "\ r \ n"; try {socket = new Socket ("192.168.0.37", 8888); // create a Socket, where the IP address is the address of my PC machine, the mobile phone accesses the Internet through wifi and the server is in the same network segment // PrintWriter out = new PrintWriter (new BufferedWriter (new // OutputStreamWrite R (socket. getOutputStream (), true); // out. println (sendMsg); // BufferedReader in = new BufferedReader (new // InputStreamReader (socket. getInputStream (); // String readMsg = in. readLine (); // if (readMsg! = Null) {// text. setText (readMsg); //} else {// text. setText ("error"); //} // out. close (); // in. close (); // socket. close (); DataOutputStream out = new DataOutputStream (socket. getOutputStream (); // sends a message out to the server. writeUTF (sendMsg); out. flush (); DataInputStream in = new DataInputStream (socket. getInputStream (); // receives the message from the Server String readMsg = in. readUTF (); if (readMsg! = Null) {text. setText (readMsg);} out. close (); in. close (); socket. close ();} catch (Exception e) {e. printStackTrace ();}}});}}
Server. java
Import java. io. bufferedReader; import java. io. bufferedWriter; import java. io. dataInputStream; import java. io. dataOutputStream; import java. io. IOException; import java. io. inputStreamReader; import java. io. outputStreamWriter; import java. io. printWriter; import java.net. serverSocket; import java.net. socket; public class Server {public Server () {new ServerThread (). start ();} class ServerThread extends Thread {public void run () {try {ServerSocket ss = new ServerSocket (8888); // create a ServerSocket object, and let the ServerSocket listen to while (true) {Socket socket = ss on port 8888. accept (); // call the accept () method of ServerSocket to accept the request sent by the client. If the client does not send data, then the thread stops and does not continue // try {// BufferedReader in = new BufferedReader (new InputStreamReader (socket. getInputStream (); // receives client information // String readline = in. readLine (); // System. out. println ("readline:" + readline); // PrintWriter out = new PrintWriter (new BufferedWriter (new OutputStreamWriter (socket. getOutputStream (), true); // out. println ("link server success"); // in. close (); // close the stream // out. close (); // close the stream // socket. close (); // close the opened socket //} catch (Exception e) {// TODO: handle exception //} finally {///socket. close (); //} try {DataInputStream in = new DataInputStream (socket. getInputStream (); // receives client information String readline = in. readUTF (); System. out. println (readline); DataOutputStream out = new DataOutputStream (socket. getOutputStream (); // sends a message out to the client. writeUTF ("link server success"); out. flush (); in. close (); // close the stream out. close (); // close the stream socket. close (); // close the opened socket} catch (Exception e) {System. out. println (e. getMessage () ;}} catch (IOException e) {System. out. println (e. getMessage () ;}} public static void main (String [] args) throws IOException {new Server (); // enable Server }}
Join multithreading: chat room
The client and the server maintain long-term communication. The server must constantly read client data and write data to the client. The client also needs to constantly read server data.
The server should beEach Socket starts a thread separately, and each thread is responsible for communicating with a client.
Server:
Package com. hust. multithred; import java. io. IOException; import java.net. serverSocket; import java.net. socket; import java. util. arrayList; public class MyServer {/*** @ param args * @ throws IOException * // The server stores the ArrayListpublic static ArrayList of all sockets.
Socketlist = new ArrayList
(); Public static void main (String [] args) throws IOException {// TODO Auto-generated method stub ServerSocket ss = new ServerSocket (3000 ); // ServerSocket listens to port 3000 while (true) {Socket socket_in_server = ss. accept (); // cyclically wait for the Socket socketlist of the client. add (socket_in_server); // each time a client Socket is received, add the Socket generated by the server to the array. // start a thread for each Socket separately, each Thread is responsible for communicating with a client. SocketThread socketthread = new SocketThread (socket_in_server); new Thread (socketthread ). start ();}}}
Package com. hust. multithred; import java. io. bufferedReader; import java. io. IOException; import java. io. inputStreamReader; import java. io. outputStream; import java.net. socket; public class SocketThread implements Runnable {// thread task class, implement the Runnable interface Socket s = null; BufferedReader br = null; public SocketThread (Socket s) throws IOException {this. s = s; br = new BufferedReader (new InputStreamReader (s. getInputStream ()));/ /The Socket input stream is packaged as a response stream. The data from the client is in this input stream and can be read by the server.} public void run () {// TODO Auto-generated method stubtry {String content = null; // The while (content = readFormClient () data sent from the client is continuously read from the Socket in a loop ())! = Null) {// after reading data, send the read content to each Socket once for (Socket s: MyServer. socketlist) {OutputStream OS = s. getOutputStream (); OS. write (content + "\ n "). getBytes ("UTF-8"); // write to the output stream of each socket }}catch (IOException e) {// TODO Auto-generated catch blocke. printStackTrace () ;}}// Method for reading data from the client from the input stream public String readFormClient () {String content = null; try {content = br. readLine ();} catch (IOException e) {// TODO Auto-generated catch blockMyServer. socketlist. remove (s) ;}return content ;}}
Client:
MainActivity. java
Package com. hust. multithreadclient; import android. app. activity; import android. OS. bundle; import android. OS. handler; import android. OS. message; import android. view. menu; import android. view. menuItem; import android. view. view; import android. view. view. onClickListener; import android. widget. button; import android. widget. editText; import android. widget. textView; public class MainActivity extends Activity {EditText input; TextView show; Button send; Handler handler; ClientThread clientthread; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); input = (EditText) findViewById (R. id. input); show = (TextView) findViewById (R. id. show); send = (Button) findViewById (R. id. send); // here, handler receives messages from sub-threads, processes messages, and updates UI handler = new Handler () {@ Override // if the Message comes from the subthread public void handleMessage (Message msg) {// TODO Auto-generated method stubif (msg. what = 0x123) {show. append ("\ n" + msg. obj. toString () ;}}; // The client starts the ClientThread Thread to create a connection and read data from the server new Thread (new ClientThread (handler )). start (); send. setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View v) {// when the user presses the send button, the data entered by the user is encapsulated into a Message and sent to the Handler of the sub-thread, handler is responsible for sending the Message msg = new Message (); msg. what = 0x111; msg. obj = input. getText (). toString (); clientthread. rvhandler. sendMessage (msg); // Handlerinput sent to the subthread. setText ("") ;}}) ;}@ Override public boolean onCreateOptionsMenu (Menu menu) {// Inflate the menu; this adds items to the action bar if it is present. getMenuInflater (). inflate (R. menu. main, menu); return true ;}@ Override public boolean onOptionsItemSelected (MenuItem item) {// Handle action bar item clicks here. the action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest. xml. int id = item. getItemId (); if (id = R. id. action_settings) {return true;} return super. onOptionsItemSelected (item );}}
ClientThread. java
Package com. hust. multithreadclient; import java. io. bufferedReader; import java. io. IOException; import java. io. inputStreamReader; import java. io. outputStream; import java.net. socket; import java.net. unknownHostException; import android. OS. handler; import android. OS. logoff; import android. OS. message; public class ClientThread implements Runnable {Socket s; Handler handler; // defines the Handler Object Handler rvhan that sends messages to the UI thread Dler; // defines the Handler object BufferedReader br = null for receiving UI thread messages; OutputStream OS = null; public ClientThread (Handler handler) {this. handler = handler;} @ Overridepublic void run () {// TODO Auto-generated method stub try {s = new Socket ("192.168.1.88", 3000 ); br = new BufferedReader (new InputStreamReader (s. getInputStream (); OS = s. getOutputStream (); // start a Thread to read data from the server. new Thread () {@ Overridepublic void run () {// TODO Auto -Generated method stubString content = null; try {while (content = br. readLine ())! = Null) {Message msg = new Message (); msg. what = 0x123; msg. obj = content; handler. sendMessage (msg); // This subthread only reads data from the server and sends it to the Handler of the UI thread for processing} catch (IOException e) {// TODO Auto-generated catch block e. printStackTrace ();}}}. start ();/** Handler in the current client thread. The communication between Android threads is Handler. * This Hnadler receives data from the UI thread, that is, user input, and write to the output stream * because this Handler receives and processes messages, you need to use logoff **/logoff. prepare (); rvhandler = new Handler () {@ Overridepublic void handleMessage (Message msg) {// if the user input data in the UI thread is received if (msg. what = 0x111) {try {// write user input in the text box to the network OS. write (msg. obj. toString () + "\ r \ n "). getBytes ("UTF-8");} catch (IOException e) {e. printStackTrace () ;}}}; logoff. loop (); // start logoff} catch (UnknownHostException e) {// TODO Auto-generated catch block e. printStackTrace ();} catch (IOException e) {// TODO Auto-generated catch block e. printStackTrace ();}}}