在Android中,可以使用Java中的Socket類來實現雙向通信。以下是使用Socket類進行雙向通信的基本步驟:
ServerSocket serverSocket = new ServerSocket(port);
Socket clientSocket = serverSocket.accept();
Socket socket = new Socket(serverIP, port);
InputStream inputStream = clientSocket.getInputStream();
OutputStream outputStream = clientSocket.getOutputStream();
InputStream inputStream = socket.getInputStream();
OutputStream outputStream = socket.getOutputStream();
// 服務器端
byte[] buffer = new byte[1024];
int bytesRead = inputStream.read(buffer);
String message = new String(buffer, 0, bytesRead);
outputStream.write(message.getBytes());
// 客戶端
String message = "Hello, server!";
outputStream.write(message.getBytes());
byte[] buffer = new byte[1024];
int bytesRead = inputStream.read(buffer);
String response = new String(buffer, 0, bytesRead);
// 服務器端
clientSocket.close();
serverSocket.close();
// 客戶端
socket.close();
請注意,這只是一個基本示例,并且可能需要進行錯誤處理和線程管理等更復雜的操作。