写一个通讯工具类
时间: 2023-10-19 14:05:11 浏览: 40
以下是一个简单的通讯工具类,可以进行网络通信:
```java
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class CommunicationTool {
private Socket socket;
private InputStream input;
private OutputStream output;
public CommunicationTool(String host, int port) throws IOException {
socket = new Socket(host, port);
input = socket.getInputStream();
output = socket.getOutputStream();
}
public void sendMessage(String message) throws IOException {
output.write(message.getBytes());
}
public String receiveMessage() throws IOException {
byte[] buffer = new byte[1024];
int length = input.read(buffer);
return new String(buffer, 0, length);
}
public void close() throws IOException {
input.close();
output.close();
socket.close();
}
}
```
使用示例:
```java
public static void main(String[] args) {
try {
CommunicationTool tool = new CommunicationTool("127.0.0.1", 8888);
tool.sendMessage("Hello, world!");
String response = tool.receiveMessage();
System.out.println("Received message: " + response);
tool.close();
} catch (IOException e) {
e.printStackTrace();
}
}
```
在此示例中,我们创建了一个客户端,并连接到了本地的 8888 端口。然后发送了一条消息 "Hello, world!",并接收了服务器返回的消息。最后关闭了连接。