java websocket连接 示例
时间: 2023-10-14 07:08:00 浏览: 142
websocket java实例
3星 · 编辑精心推荐
好的,我可以为您提供Java WebSocket连接的示例。以下是一个简单的Java WebSocket服务器和客户端示例:
Server端示例:
```
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;
public class Server extends WebSocketServer {
public static void main(String[] args) throws Exception {
WebSocketServer server = new Server(new InetSocketAddress(9000));
server.start();
}
public Server(InetSocketAddress address) {
super(address, Executors.newSingleThreadExecutor());
}
@Override
public void onOpen(WebSocket conn, ClientHandshake handshake) {
System.out.println("Client connected: " + conn.getRemoteSocketAddress());
}
@Override
public void onClose(WebSocket conn, int code, String reason, boolean remote) {
System.out.println("Client disconnected: " + conn.getRemoteSocketAddress());
}
@Override
public void onMessage(WebSocket conn, String message) {
System.out.println("Got message from client: " + message);
conn.send("Message received: " + message);
}
@Override
public void onError(WebSocket conn, Exception ex) {
System.out.println("Error occurred: " + ex.getMessage());
}
}
```
Client端示例:
```
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
public class Client extends WebSocketClient {
public Client(URI serverUri) {
super(serverUri);
}
@Override
public void onOpen(ServerHandshake handshakedata) {
System.out.println("Connected to server: " + this.getURI());
}
@Override
public void onClose(int code, String reason, boolean remote) {
System.out.println("Disconnected from server: " + reason);
}
@Override
public void onMessage(String message) {
System.out.println("Got message from server: " + message);
}
@Override
public void onError(Exception ex) {
System.out.println("Error occurred: " + ex.getMessage());
}
public static void main(String[] args) throws URISyntaxException, IOException {
Client client = new Client(new URI("ws://localhost:9000"));
client.connect();
BufferedReader sysIn = new BufferedReader(new InputStreamReader(System.in));
String userInput;
while ((userInput = sysIn.readLine()) != null && !userInput.equals("exit")) {
client.send(userInput);
}
}
}
```
你可以在运行Server端程序之后再运行Client端程序,然后在Client端程序中输入一些消息,就可以在Server端程序中查看到这些消息了。
阅读全文