jdk17 搭建websocket服务端,可以给特定或者指定的客户端发送信息,或者接收客户端消息,详细输出完整代码,不要省略逻辑和代码
时间: 2024-11-16 14:19:29 浏览: 15
基于springboot实现websocket客户端和服务端
在Java 17中,我们可以使用Java WebSocket API(JSR 356)来创建WebSocket服务器。以下是一个简单的例子,展示了如何使用`javax.websocket`包来实现一个WebSocket服务器,该服务器能接收到特定客户端的消息并广播给所有连接。
首先,你需要添加WebSocket的依赖到你的项目中。如果你使用的是Maven,可以在pom.xml文件中添加:
```xml
<dependencies>
<dependency>
<groupId>javax.websocket</groupId>
<artifactId>javax.websocket-api</artifactId>
<version>1.1</version>
<!-- For Tomcat server, use -->
<scope>provided</scope>
</dependency>
<!-- For a standalone server like Jetty or Undertow, add this -->
<dependency>
<groupId>org.glassfish.tyrus.bundles</groupId>
<artifactId>tyrus-standalone-server-jetty</artifactId>
<version>1.19.0</version>
</dependency>
</dependencies>
```
接下来,我们创建一个WebSocket服务器端点(Endpoint):
```java
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import java.io.IOException;
public class ChatServerEndpoint implements Endpoint {
private static final Set<Session> clients = new HashSet<>();
@OnOpen
public void onOpen(Session session) {
System.out.println("New connection from: " + session.getId());
clients.add(session);
}
@OnMessage
public String handleMessage(String message, Session sender) {
System.out.println("Received message: " + message + " from: " + sender.getId());
// Broadcasting the message to all connected clients
for (Session client : clients) {
if (!client.equals(sender)) { // Avoid sending to the sender
try {
client.getBasicRemote().sendText(message);
} catch (IOException e) {
System.err.println("Failed to send message to " + client.getId() + ": " + e.getMessage());
}
}
}
return "Message received";
}
@OnClose
public void onClose(Session session, CloseReason reason) {
System.out.println("Connection closed by " + session.getId() + ": " + reason);
clients.remove(session);
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof ChatServerEndpoint)) return false;
return this == obj || ((ChatServerEndpoint) obj).getId().equals(this.getId());
}
// Assuming you have an id method that returns a unique identifier for the endpoint
public String getId() {
// ...
}
}
```
这个`ChatServerEndpoint`类实现了`Endpoint`接口,其中包含三个回调方法:
- `onOpen()`:当新连接打开时调用,添加到`clients`集合中。
- `handleMessage()`:处理客户端发送的消息,广播给所有其他连接的客户端。
- `onClose()`:关闭连接时调用,从`clients`集合中移除。
为了启动WebSocket服务器,你需要创建一个`ServerContainer`实例并部署你的`ChatServerEndpoint`:
```java
import jakarta.websocket.DeploymentException;
import jakarta.websocket.server.ServerContainer;
import jakarta.websocket.server.ServerEndpointConfig;
public class Main {
public static void main(String[] args) {
ServerContainer container = ContainerProvider.getWebSocketContainer();
container.deploy(ServerEndpointConfig.Builder.create(ChatServerEndpoint.class)
.configurator(new LoggingConfigurator())
.build());
System.out.println("WebSocket server started.");
container.startup();
}
// Custom configurator for logging or other setup
private static class LoggingConfigurator extends AbstractEndpointConfig.Configurator {
@Override
public void modifyMetadata(Metadata metadata) {
super.modifyMetadata(metadata);
// Log additional configuration here
}
}
}
```
这里假设你使用了Jetty或Undertow等支持WebSocket的容器。记住,如果是在Tomcat等容器上运行,可能需要检查是否已经启用WebSocket支持。
阅读全文