以下是我的WebSockets客户端脚本。在这段代码中,我定义了一个带有IP地址和端口的WebSockets对象。
客户端脚本:
var webSocket =
new WebSocket('ws://localhost:8080/Spring4JSONHandling/websocket');
webSocket.onmessage = function processMessage(message)
{
var jsonData = JSON.parse(message.data);
jsonforlogout = jsonData;
//var user=JSON.parse(username.data);
console.log(jsonData); //to print
if (jsonData.message != null){
var msgAdd = JSON.stringify(jsonData.message);
msgAdd = msgAdd.replace(/[&\/\\#,+()$~%.'"*?<>{}]/g, '');
alert("3"+msgAdd);
var xyz = msgAdd.split(" : ");
var logged = '${me}';
alert("logged" + logged);
alert("xyz[0]" + xyz[0]);
if (logged == xyz[0]){
alert("1");
$("#chat" + xyz[0]).chatbox("option", "boxManager").addMsg(xyz[0], xyz[1]);
} else{
alert("2");
$("#chat" + xyz[0]).chatbox("option", "boxManager").addMsg(xyz[0], xyz[1]);
}
}
/* if(jsonData.message=='close'){websocket.close();} */
if (jsonData.users != null)
{
document.getElementById("chatusers").innerHTML = "";
var loggedInUser = '${me}';
var i = 0;
while (i < jsonData.users.length)
{
var onlineAdd = JSON.stringify(jsonData.users[i]);
onlineAdd = onlineAdd.replace(/[&\/\\#,+()$~%.'":*?<>{}]/g, '');
if (loggedInUser != onlineAdd){
var clone = "<a href='#' onclick=\"clickFun('" + onlineAdd.trim() + "');\" class='usr' data-chat-id='chat" + onlineAdd + "' data-chat-fname='" + onlineAdd + "' data-chat-lname='" + onlineAdd + "'"
+ " data-chat-status='online' data-chat-alertmsg='' data-chat-alertshow='true' data-rel='popover-hover' data-placement='right' data-html='true'"
+ " data-content=\"<div class='usr-card'>"
+ "<img src='Spring4JSONHandling/resources/img/1.png' alt='Jessica Dolof'>"
+ "<div class='usr-card-content'>"
+ "<h3>Jessica Dolof</h3>"
+ "<p>Sales Administrator</p>"
+ "</div>"
+ "</div>\"><i></i>" + onlineAdd + "</a>";
$('#chatusers').append(clone);
}
i++;
}
}
//or(i = 0; i < responselist.data.length; i++) {
/* var i=0;
while(i<jsonData.users.length)
{
var comboitem = document.createElement("option");
comboitem.text = jsonData.users[i];//"utsav";//
comboitem.value = jsonData.users[i];//"10";
usercombo.options.add(comboitem);
i++;
} */
}
function sendMessage(txt) {
//alert(messageText.value+ " h1");
webSocket.send(txt);
// messageText.value = "";
}
window.onbeforeunload = function () {
webSocket.onclose = function() {};
webSocket.close();
};
以下是服务器端点的代码。在这段代码中,我已经定义了一个带有服务器端点的WebSockets对象。
服务器代码:
package com.outbottle.controllers;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import javax.json.Json;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObject;
import javax.json.JsonWriter;
import javax.servlet.http.HttpSession;
import javax.websocket.EndpointConfig;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
@ServerEndpoint("/websocket")
public class WebSocketTest {
static Set<Session> chatroomUsers= Collections.synchronizedSet(new HashSet<Session>());
private final static HashMap<String, WebSocketTest> sockets = new HashMap<>();
private String myUniqueId;
private String getMyUniqueId() {
// unique ID from this class' hash code
return Integer.toHexString(this.hashCode());
}
@OnOpen
public void handleOpen(Session userSession) throws IOException {
chatroomUsers.add(userSession);
System.out.println("user added"); //user added
this.myUniqueId = this.getMyUniqueId();
System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"+ myUniqueId);
WebSocketTest.sockets.put(this.myUniqueId, this);
System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"+sockets);
}
@OnMessage
public void handleMessage(String message, Session userSession) throws IOException{
String username= (String) userSession.getUserProperties().get("username");
Iterator<Session> itr=chatroomUsers.iterator();
if(username==null){
userSession.getUserProperties().put("username", message);
userSession.getBasicRemote().sendText(buildJsonMessageData("System","You are now connected as "+message));
while (itr.hasNext()) (itr.next()).getBasicRemote().sendText(buildJsonUsersData()); }
else {
while (itr.hasNext()) {
itr.next().getBasicRemote().sendText(buildJsonMessageData(username,message));
}
}
}
@OnClose
public void handleClose(Session userSession) throws IOException {
// TODO Auto-generated method stub
System.out.println("user logout");
chatroomUsers.remove(userSession);
Iterator<Session> itr = chatroomUsers.iterator();
while (itr.hasNext()) (itr.next()).getBasicRemote().sendText(buildJsonUsersData());
}
private String buildJsonUsersData() {
Iterator<String> itr= getUserNames().iterator();
JsonArrayBuilder jsonArrayBuilder = Json.createArrayBuilder();
while (itr.hasNext()) jsonArrayBuilder.add((String)itr.next());
return Json.createObjectBuilder().add("users", jsonArrayBuilder).build().toString();
}
private String buildJsonMessageData(String username, String message)
{
JsonObject jsonObject=Json.createObjectBuilder().add("message", username+" : "+ message).build();
StringWriter stringWriter= new StringWriter();
try (JsonWriter jsonWriter = Json.createWriter(stringWriter)){
jsonWriter.write(jsonObject);
}
return stringWriter.toString();
}
private Set<String> getUserNames()
{
HashSet<String> returnSet = new HashSet<String>();
Iterator<Session> itr= chatroomUsers.iterator();
System.out.println("@@@@@@@@@@@@@@@@@@@@@@");
while (itr.hasNext())
{
returnSet.add(itr.next().getUserProperties().get("username").toString());
}
return returnSet;
}
}
问题是当我在不同的IP上向用户发送消息时,所有具有相同名称的用户都会收到消息。我只需要将消息发送到特定会话。
答案 0 :(得分:0)
看起来您正在遍历chatroomUsers
函数中的所有会话handleMessage
。
如果您只想将消息发送给特定用户/会话,那么您是否需要在此处检查username
属性?