android------- socket realizes client-server communication

The introduction and principle of Socket were introduced earlier. Today, we will simply implement the function of communication between the client and the server.

 

Kefuduan

establish connection

 try {
socket
= new Socket("192.168.1.100", 9999); Log.i( "Android", "Connect with server: " + socket); } catch (UnknownHostException e) { e.printStackTrace (); } catch (IOException e) { e.printStackTrace (); }

 

send messages

  try {
         // socket.getInputStream()
        DataOutputStream writer = new DataOutputStream(socket.getOutputStream());
        writer.writeUTF( "Hey, hello, server.."); // Write a UTF-8 message 
        System.out.println( "Send message" );
      } catch (IOException e) {
           e.printStackTrace ();
      }

 

Add permission

 <uses-permission android:name="android.permission.INTERNET"/>

 

Server (you can create a Java project in Eclipse)

import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class SocketServer {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        
        System.out.println("123456");
        startService();
    }
    
    
    /**  
    * Start the service listening, waiting for the client to connect
    */  
   private static void startService() {  
       try {  
           // 创建ServerSocket  
           ServerSocket serverSocket = new ServerSocket(9999);  
           System.out.println( "--Start the server, listen on port 9999--" );  
 
           // Listen on the port and wait for the client to connect   
           while ( true ) {  
               System.out.println( "--waiting for client connection--" );  
               Socket socket = serverSocket.accept(); // Waiting for client connection   
               System.out.println("Get client connection: " + socket);  
                 
               startReader(socket);  
           }  
 
       } catch (IOException e) {  
           e.printStackTrace ();  
       }  
   }  
 
   /**  
    * Get the latest news from the parameter's Socket
    */  
   private static void startReader(final Socket socket) {  
 
       new Thread(){  
           @Override  
           public void run() {  
               DataInputStream reader;  
               try {  
                    // Get the read stream   
                   reader = new DataInputStream( socket.getInputStream());  
                    while ( true ) {  
                       System.out.println( "*Wait for client input*" );  
                        // Read data   
                       String msg = reader.readUTF();  
                       System.out.println( "Get client information: " + msg);  
                   }  
               } catch (IOException e) {  
                   e.printStackTrace ();  
               }  
           }  
       }.start();  
   }  

}

 

Run the Java project and get

 

 

Then click send message on the phone

     

 

 

The server receives the message and prints the information

 

 

Server sends message to client

 

Server code:

public  class TestServer {

     public static void main(String[] args) {
        
         try {
            ServerSocket serverSocket = new ServerSocket(30000);
            System.out.println( "Server is connected" );
             while ( true ){
                System.out.println("123");
                Socket socket = serverSocket.accept();
                OutputStream outputStream = socket.getOutputStream();
                outputStream.write( "Hello, I'm the server\n".getBytes("utf-8" ));
                outputStream.close();
                socket.close();
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
         
     }
}

 

client code

public class Demo2Activity extends AppCompatActivity {

    static TextView textView;
    Socket socket;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.demo2);
        initView();
    }


    private void initView(){
        textView = (TextView) findViewById(R.id.txt_1);

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    socket = new Socket("192.168.1.101", 30000 );
                     // socket.setSoTimeout(10000); // Set 10 seconds timeout 
                    Log.i("Android", "Connect with server: " + socket);
                    BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    String line = br.readLine();
                    Log.i( "Android", "Connect to the server: " + line);
                    Message msg = new Message();
                    msg.what = 1;
                    msg.obj = line;
                    handler.sendMessage(msg);
                } catch (UnknownHostException e) {
                    e.printStackTrace ();
                } catch (IOException e) {
                    e.printStackTrace ();
                }catch (Exception e){
                    e.printStackTrace ();
                }
            }
        }).start();

    }

    Handler handler = new Handler () {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1){
                textView.setText( "This is the data from the server: "+ msg.obj.toString());
            }
        }
    };

}

 

 

Run the server first, then run the client

Effect picture:

 

 

 

 

The source code contains multiple demos, which are also based on online materials.

 

Source address: https://github.com/DickyQie/android-socket

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324659988&siteId=291194637