java websocket 连接 服务端
时间: 2023-12-21 12:30:13 浏览: 102
以下是Java WebSocket连接服务端的示例代码:
```java
import java.net.URI;
import java.net.URISyntaxException;
import java.util.concurrent.CountDownLatch;
import javax.websocket.ClientEndpoint;
import javax.websocket.CloseReason;
import javax.websocket.ContainerProvider;
import javax.websocket.DeploymentException;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;
@ClientEndpoint
public class WebSocketClient {
private Session session;
private CountDownLatch latch;
public WebSocketClient() {
this.latch = new CountDownLatch(1);
}
public void connect(String uri) throws DeploymentException, URISyntaxException, InterruptedException {
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
container.connectToServer(this, new URI(uri));
latch.await();
}
@OnOpen
public void onOpen(Session session) {
this.session = session;
System.out.println("Connected to server");
latch.countDown();
}
@OnMessage
public void onMessage(String message) {
System.out.println("Received message: " + message);
}
@OnClose
public void onClose(CloseReason reason) {
System.out.println("Disconnected from server: " + reason.getReasonPhrase());
}
public void sendMessage(String message) throws Exception {
this.session.getBasicRemote().sendText(message);
}
}
```
在上面的示例中,我们使用了Java API中的javax.websocket包来实现WebSocket客户端。在客户端代码中,我们定义了一个WebSocketClient类,并使用@ClientEndpoint注解将其标记为WebSocket客户端。我们还定义了一些方法来处理WebSocket事件,例如onOpen()、onMessage()和onClose()。
要连接WebSocket服务器,我们需要调用WebSocketContainer的connectToServer()方法,并传递一个实例化的WebSocketClient对象和WebSocket服务器的URI。在连接成功后,onOpen()方法将被调用,并且我们可以使用session对象来发送消息到WebSocket服务器。
以下是一个使用WebSocketClient类连接WebSocket服务器的示例代码:
```java
public static void main(String[] args) throws Exception {
WebSocketClient client = new WebSocketClient();
client.connect("ws://localhost:8080/myapp/websocket");
client.sendMessage("Hello, WebSocket server!");
}
```
在上面的示例中,我们实例化了一个WebSocketClient对象,并调用了connect()方法来连接WebSocket服务器。在连接成功后,我们使用sendMessage()方法向WebSocket服务器发送一条消息。
阅读全文