What is the method for encapsulating sockets in Android…

In Android, you can use Java’s Socket class for network communication. Below is a simple example of encapsulation method.

Create a class named SocketClient:

public class SocketClient {
    private Socket socket;
    private BufferedReader reader;
    private BufferedWriter writer;

    public SocketClient() {
        try {
            // 创建Socket对象
            socket = new Socket("服务器IP地址", 服务器端口号);

            // 创建输入输出流
            reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public String sendMessage(String message) {
        try {
            // 发送消息
            writer.write(message + "\n");
            writer.flush();

            // 接收服务器返回的消息
            String response = reader.readLine();
            return response;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public void close() {
        try {
            // 关闭输入输出流和Socket连接
            writer.close();
            reader.close();
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

2. Create a SocketClient object where you need to use Socket, and call the sendMessage method to send a message and receive the response from the server.

SocketClient client = new SocketClient();
String response = client.sendMessage("要发送的消息");
client.close();

This is a simple example of a Socket encapsulation method, which may need to be modified and improved according to actual needs during implementation.

bannerAds