websocket - How to send message to a particular session using web socket in java? -
here below client side script websockets. in code have defined websockets object ip address , port.
client script:
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 = 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; < 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(); };
here code server end point. in code have defined websockets object server endpoint.
server code:
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 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 connected "+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; } }
the problem when send message user on different ip, users same name message. need send message particular session only.
it looks iterating through sessions chatroomusers
in handlemessage
function.
if want send message particular user/session, not need check username
property here?
Comments
Post a Comment