ESP8266与Android通信简单TCP服务端设计

首先需要导入包:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

其次在代码中建立如下代码,就可以在DEBUG信息中看到通信信息。

public class SocketServer {
    private static final  int SERVER_PORT = 12345;

    public static void main(){
        try{
            System.out.println("Server: Connecting..");
            ServerSocket serverSocket = new ServerSocket(SERVER_PORT);
            while(true){
                Socket clientSocket = serverSocket.accept();
                System.out.println("Server:Receiving...");
                try {
                    BufferedReader in = new BufferedReader(
                            new InputStreamReader(clientSocket.getInputStream())
                    );
                    String str = in.readLine();
                    System.out.println("Server:Received: '"+str+"'");
                }catch(Exception e){
                    System.out.println("Server:Error");
                    e.printStackTrace();
                }finally {
                    clientSocket.close();
                    System.out.println("Server:Close.");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

你可能感兴趣的:(Java,ESP8266)