java js websocket_javascript – 如何使用java服务器将消息发送到特定的websocket连接

本文介绍了如何设计一个WebSocket服务器架构,当客户端连接时,服务器会保持连接并使用用户ID或套接字对象作为唯一标识符。数据结构采用HashMap来存储和查找连接,允许广播消息给所有客户端或特定客户端。在连接关闭时,会从数据结构中移除,并通知其他客户端。示例代码展示了使用Jetty9WebSocket实现的详细过程。
摘要由CSDN通过智能技术生成

你必须为此设计一个架构.

当客户端建立与服务器的连接(打开WebSocket)时,服务器必须将连接保持在某个位置(无论您使用Java后端识别与您所使用的Java后端的特定连接),数据结构将依赖于你想做什么一个好的标识符就是用户提供的ID(比如连接到同一个服务器的另一个对等体尚未选择的昵称).否则,只需使用套接字对象作为唯一标识符,并且在前端列出其他用户时,将它们与其唯一标识符相关联,以便客户端可以向特定对等体发送消息.

如果客户端要与另一个特定客户端进行聊天,则HashMap将是数据结构的不错选择,因为您可以将客户端的唯一ID映射到套接字,并在散列表中找到O(1)中的条目.

如果要将客户端的消息广播到所有其他客户端,虽然HashMap也可以很好地运行(如HashMap.values()),但您可以使用一个简单的列表,将传入的消息发送到除原始发件人之外的所有连接的客户端.

当然,您也想从数据结构中删除一个客户端,当您丢失与它的连接时,这很容易使用WebSocket(您正在使用的Java框架应该在套接字关闭时回拨).

这是一个使用Jetty 9 WebSocket(和JDK 7)的(几乎完整的)示例:

package so.example;

import java.io.IOException;

import java.util.HashMap;

import org.eclipse.jetty.websocket.api.Session;

import org.eclipse.jetty.websocket.api.annotations.OnWebSocketClose;

import org.eclipse.jetty.websocket.api.annotations.OnWebSocketConnect;

import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage;

import org.eclipse.jetty.websocket.api.annotations.WebSocket;

@WebSocket

public class MyWebSocket {

private final static HashMap sockets = new HashMap<>();

private Session session;

private String myUniqueId;

private String getMyUniqueId() {

// unique ID from this class' hash code

return Integer.toHexString(this.hashCode());

}

@OnWebSocketConnect

public void onConnect(Session session) {

// save session so we can send

this.session = session;

// this unique ID

this.myUniqueId = this.getMyUniqueId();

// map this unique ID to this connection

MyWebSocket.sockets.put(this.myUniqueId, this);

// send its unique ID to the client (JSON)

this.sendClient(String.format("{\"msg\": \"uniqueId\", \"uniqueId\": \"%s\"}",

this.myUniqueId));

// broadcast this new connection (with its unique ID) to all other connected clients

for (MyWebSocket dstSocket : MyWebSocket.sockets.values()) {

if (dstSocket == this) {

// skip me

continue;

}

dstSocket.sendClient(String.format("{\"msg\": \"newClient\", \"newClientId\": \"%s\"}",

this.myUniqueId));

}

}

@OnWebSocketMessage

public void onMsg(String msg) {

/*

* process message here with whatever JSON library or protocol you like

* to get the destination unique ID from the client and the actual message

* to be sent (not shown). also, make sure to escape the message string

* for further JSON inclusion.

*/

String destUniqueId = ...;

String escapedMessage = ...;

// is the destination client connected?

if (!MyWebSocket.sockets.containsKey(destUniqueId)) {

this.sendError(String.format("destination client %s does not exist", destUniqueId));

return;

}

// send message to destination client

this.sendClient(String.format("{\"msg\": \"message\", \"destId\": \"%s\", \"message\": \"%s\"}",

destUniqueId, escapedMessage));

}

@OnWebSocketClose

public void onClose(Session session, int statusCode, String reason) {

if (MyWebSocket.sockets.containsKey(this.myUniqueId)) {

// remove connection

MyWebSocket.sockets.remove(this.myUniqueId);

// broadcast this lost connection to all other connected clients

for (MyWebSocket dstSocket : MyWebSocket.sockets.values()) {

if (dstSocket == this) {

// skip me

continue;

}

dstSocket.sendClient(String.format("{\"msg\": \"lostClient\", \"lostClientId\": \"%s\"}",

this.myUniqueId));

}

}

}

private void sendClient(String str) {

try {

this.session.getRemote().sendString(str);

} catch (IOException e) {

e.printStackTrace();

}

}

private void sendError(String err) {

this.sendClient(String.format("{\"msg\": \"error\", \"error\": \"%s\"}", err));

}

}

代码是自解释的.关于JSON格式化和解析,Jetty在包org.eclipse.jetty.util.ajax中有一些有趣的工具.

还要注意,如果您的WebSocket服务器框架不是线程安全的,则需要同步数据结构,以确保没有数据损坏(这里是MyWebSocket.sockets).

Java中的WebSocket消息发送是通过WebSocket API实现的,这是HTML5的一部分,提供了在客户端和服务器之间进行全双工通信的协议。在Java中,可以利用Java WebSocket API(JSR 356)实现WebSocket通信。 在Java WebSocket中,消息发送的基本流程如下: 1. 注册WebSocket端点:在服务器端,你需要创建一个类并使用`@ServerEndpoint`注解来声明它是一个WebSocket服务器端点。 2. 客户端连接:客户端使用WebSocket API连接服务器端点。 3. 服务器发送消息:在服务器端点的方法中,你可以使用`Session`对象来发送消息到客户端。`Session`对象由服务器自动提供,代表了与特定客户端的连接。 4. 客户端接收消息:客户端的WebSocket实现需要在连接上设置消息处理的回调函数,以便接收服务器发送消息。 下面是一个简单的Java WebSocket消息发送示例: ```java // 服务器端 import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.ServerEndpoint; @ServerEndpoint("/chat") public class ChatEndpoint { @OnOpen public void onOpen(Session session) { // 当新的WebSocket连接打开时调用 // 可以发送消息给客户端 session.getBasicRemote().sendText("欢迎来到聊天室!"); } } // 客户端(使用JavaScript示例) const socket = new WebSocket('ws://服务器地址/chat'); socket.onmessage = function(event) { // 当接收到服务器发送消息时调用 const message = event.data; console.log("来自服务器消息: " + message); }; ``` 在上述示例中,服务器端点`ChatEndpoint`当连接打开时会发送一条欢迎信息到客户端。客户端使用JavaScript创建了WebSocket连接,并设置了一个回调函数来接收消息
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值