帮我写一个JavaTCP工具类
时间: 2023-04-06 09:02:31 浏览: 217
好的,我可以回答这个问题。以下是一个简单的JavaTCP工具类的示例:
```
import java.io.*;
import java.net.*;
public class TCPTool {
public static void send(String message, String ipAddress, int port) throws IOException {
Socket socket = new Socket(ipAddress, port);
OutputStream out = socket.getOutputStream();
PrintWriter writer = new PrintWriter(out);
writer.println(message);
writer.flush();
socket.close();
}
public static String receive(int port) throws IOException {
ServerSocket serverSocket = new ServerSocket(port);
Socket socket = serverSocket.accept();
InputStream in = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String message = reader.readLine();
socket.close();
serverSocket.close();
return message;
}
}
```
这个工具类包含了两个方法,一个用于发送消息,一个用于接收消息。你可以使用这个工具类来实现TCP通信。
阅读全文