帮我写一个单例模式javasocket客户端
时间: 2023-10-07 11:04:18 浏览: 87
好的,以下是单例模式JavaSocket客户端的示例代码:
```
public class SocketClient {
private static SocketClient instance;
private Socket socket;
private SocketClient() {
// 私有构造函数
}
public static SocketClient getInstance() {
if (instance == null) {
instance = new SocketClient();
}
return instance;
}
public void connect(String host, int port) throws IOException {
socket = new Socket(host, port);
}
public void send(String message) throws IOException {
OutputStream out = socket.getOutputStream();
out.write(message.getBytes());
}
public String receive() throws IOException {
InputStream in = socket.getInputStream();
byte[] buffer = new byte[1024];
int len = in.read(buffer);
return new String(buffer, 0, len);
}
public void disconnect() throws IOException {
socket.close();
}
}
```
使用示例:
```
SocketClient client = SocketClient.getInstance();
client.connect("localhost", 8080);
client.send("Hello, server!");
String response = client.receive();
client.disconnect();
```
以上代码实现了一个单例模式的JavaSocket客户端,并提供了连接、发送、接收和断开连接等功能。如果您需要更详细的说明,请随时提问。
阅读全文