用Android代码完成下列要求:服务端Tcp协议监听9100端口,客户端向服务端发送00,服务端接收到之后回复32
时间: 2024-05-15 20:19:59 浏览: 72
安卓TCP服务端代码
5星 · 资源好评率100%
服务端代码:
```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class TcpServer {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(9100);
System.out.println("Server started, waiting for client...");
while (true) {
Socket socket = serverSocket.accept();
System.out.println("Client connected");
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String message = in.readLine();
System.out.println("Received message: " + message);
if (message.equals("00")) {
OutputStream out = socket.getOutputStream();
out.write("32".getBytes());
out.flush();
}
socket.close();
System.out.println("Client disconnected");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
客户端代码:
```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
public class TcpClient {
public static void main(String[] args) {
String host = "localhost";
int port = 9100;
try {
Socket socket = new Socket(host, port);
System.out.println("Connected to server");
OutputStream out = socket.getOutputStream();
out.write("00".getBytes());
out.flush();
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String message = in.readLine();
System.out.println("Received message: " + message);
socket.close();
System.out.println("Disconnected from server");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
阅读全文