Sahil Sahil - 7 months ago 30
HTML Question

Web Chat with a particular user through websocket in java

I dont know enough about websocket programming but somehow by watching youtube i made a chat application which is basically a group chat but now i want to chat with a particular user not with the whole group. I know i have to generate a unique id of every person but how can i now connect to another please help and tell me about the api too which i have to download??

Here is my code

package websocket;



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.websocket.OnClose;

import javax.websocket.OnMessage;

import javax.websocket.OnOpen;

import javax.websocket.Session;

import javax.websocket.server.ServerEndpoint;

import org.json.JSONException;


public class ChatroomServerEndPoint {

static Set<Session> chatroomUsers= Collections.synchronizedSet(new HashSet<Session>());

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

private String myUniqueId;

private String getMyUniqueId() {
// unique ID from this class' hash code
return Integer.toHexString(this.hashCode());

public void handleOpen(Session userSession) throws IOException {
System.out.println("user added"); //user added
this.myUniqueId = this.getMyUniqueId();

System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"+ myUniqueId);
ChatroomServerEndPoint.sockets.put(this.myUniqueId, this);

public void handleMessage(String message, Session userSession) throws IOException, JSONException{
String username= (String) userSession.getUserProperties().get("username");
Iterator<Session> itr=chatroomUsers.iterator();
userSession.getUserProperties().put("username", message);
userSession.getBasicRemote().sendText(buildJsonMessageData("System","You are now connected as "+message));
while (itr.hasNext()) (; }
else {

while (itr.hasNext()) {,message));


public void handleClose(Session userSession) throws IOException {
// TODO Auto-generated method stub
System.out.println("user logout");
Iterator<Session> itr = chatroomUsers.iterator();
while (itr.hasNext()) (;

private String buildJsonUsersData() {

Iterator<String> itr= getUserNames().iterator();
JsonArrayBuilder jsonArrayBuilder = Json.createArrayBuilder();

while (itr.hasNext()) jsonArrayBuilder.add((String);

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)){

return stringWriter.toString();

private Set<String> getUserNames()
HashSet<String> returnSet = new HashSet<String>();

Iterator<Session> itr= chatroomUsers.iterator();

while (itr.hasNext())

return returnSet;


enter code here


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">



<script type="text/javascript">

var jsonforlogout;


var websocket =new


websocket.onmessage = function processMessage(message)


var jsonData = JSON.parse(;


//var user=JSON.parse(;

console.log(jsonData); //to print

if(jsonData.message!=null) messagesTextArea.value += jsonData.message +"\n";
/* if(jsonData.message=='close'){websocket.close();} */
var usercombo = document.getElementById("usercombo"); //combo
usercombo.length = 0;

var i=0;
usersTextArea.value += jsonData.users[i] + "\n";
var comboitem = document.createElement("option");
comboitem.text = jsonData.users[i];//"utsav";//
comboitem.value = jsonData.users[i];//"10";

//or(i = 0; i <; i++) {
/* var i=0;
var comboitem = document.createElement("option");
comboitem.text = jsonData.users[i];//"utsav";//
comboitem.value = jsonData.users[i];//"10";
} */

function sendMessage() {
//alert(messageText.value+ " h1");
window.onbeforeunload = function () {
websocket.onclose = function() {};

/* function logout()
messagesTextArea.value +=jsonforlogout.message+ "\n ####logout####" + "\n";
//document.getElementById("messagesTextArea").value+="logout ####";
} */

<title>Insert title here</title>
<div align= "center" style="color:orange;font-size: 8mm;">
WebChat Server
<div align="center" >
<textarea id="messagesTextArea" readonly="readonly" rows="15" cols="70" style="color: red;font-size:15pt;" ></textarea>
<textarea id="usersTextArea" readonly="readonly" rows="15" cols="20" style="color: blue;font-size:15pt;text-align: center;"></textarea>
<input type="text" id="messageText" size="50" onkeydown="if (event.keyCode == 13) { sendMessage(); }">
<input type="button" value="send" onclick="sendMessage();">
<!-- <input type="button" value="logout" onclick="logout();"> -->
To:<select id="usercombo" name="usercombo" >


Follow this sample code bellow, all you need is to store each user session in a buffer and get the session using key/value pair

@ServerEndpoint("/chat") public class CampusianChat { // set to store all the live sessions private static final Set<Session> sessions = Collections.synchronizedSet(new HashSet<Session>());

// Mapping between session and person name
private static final HashMap<String, String> nameSessionPair = new HashMap<String, String>();

// Getting query params
public static Map<String, String> getQueryMap(String query) {
Map<String, String> map = new HashMap<String, String>();//Maps.newHashMap();
if (query != null) {
        String[] params = query.split("&");
        for (String param : params) {
    String[] nameval = param.split("=");
    map.put(nameval[0], nameval[1]);
return map;

private String message = "";
private String to = "";
private String from = "";

public void open(Session session) {
    System.out.println("Connected with session ID "+session.getId()+" : "+session.getQueryString());
    Map<String, String> campusian = getQueryMap(session.getQueryString());
    String campusianName = "";
    if (campusian.containsKey("name")) {
        campusianName = campusian.get("name");
        try {
            campusianName = URLDecoder.decode(campusianName, "UTF-8");
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(CampusianChat.class.getName()).log(Level.SEVERE, null, ex);
        //Mapping session ID with campusian
        nameSessionPair.put(campusianName, session.getId());

public void message(String message, Session session) {
    //Get Gson string as message
    Gson gson = new Gson();
    Campusian campusian = gson.fromJson(message, Campusian.class);
    //Get the message, from (the sender) and to (the user you are sending the msg to)
    this.message = campusian.getMessage();
    this.from = campusian.getFrom(); = campusian.getTo();
    System.out.println("From: "+from);
    System.out.println("To: "+to);
    try {
        for (Session s : sessions) {
             //Check for the recepient session id. If it exist send message
            if (nameSessionPair.get( {
                Campusian c = new Campusian();

                //Send message in Gson as string

    } catch (IOException ex) {
        Logger.getLogger(CampusianChat.class.getName()).log(Level.SEVERE, null, ex);

public void close(Session session) {



//This class is used for parsing Gson string public class Campusian { String message; String to; String from;

 public void setMessage(String message) {
   this.message = message;
 public String getMessage() {
  return this.message;
public void setTo(String to) { = to;
 public String getTo() {
public void setFrom(String from) {
   this.from = from;
 public String getFrom() {
  return this.from;