man*_*khh 10 javascript websocket
我是WebSockets的新手.
我已经在WebSockets中进行了简单的服务器 - 客户端聊天.
现在我正在尝试制作客户端 - 服务器 - 客户端聊天应用程序.
我有一个问题,在java服务器中我们如何向特定的WebSocket连接发送消息.
如果用户-A想要向User-B发送消息.
那么我该如何管理User-B正在使用这个或那个连接或者向该特定连接发送消息?
我在谷歌搜索太多了,但找不到任何好的东西.
eep*_*epp 19
你必须为此设计一个架构.
当客户端与服务器建立连接(打开WebSocket)时,服务器必须在某个地方保持连接(无论您使用正在使用的Java后端识别特定连接),在依赖于的数据结构中你想做什么.一个好的标识符就是用户提供的ID(比如连接到同一服务器的另一个对等方尚未选择的昵称).否则,只需使用套接字对象作为唯一标识符,并且在列出前端上的其他用户时,将它们与其唯一标识符相关联,以便客户端可以向特定对等方发送消息.
A HashMap
would be a good choice for a data structure if a client is going to chat with another specific client, as you can map the unique ID of a client to the socket and find an entry with in O(1) in a hash table.
If you want to broadcast a message from a client to all other clients, although a HashMap
would also work pretty well (with something like HashMap.values()
), you may use a simple List
, sending the incoming message to all connected clients except the original sender.
Of course, you also want to remove a client from the data structure when you lose connection with it, which is easy using a WebSocket (the Java framework you are using should call you back when a socket closes).
Here's an (almost complete) example using a Jetty 9 WebSocket (and 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<String, MyWebSocket> 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));
}
}
Run Code Online (Sandbox Code Playgroud)
代码是自我解释的.关于JSON格式化和解析,Jetty在包中有一些有趣的实用程序org.eclipse.jetty.util.ajax
.
另请注意,如果您的WebSocket服务器框架不是线程安全的,则需要同步数据结构以确保没有数据损坏(此处MyWebSocket.sockets
).
归档时间: |
|
查看次数: |
21779 次 |
最近记录: |