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

ChatroomServerEndPoint.java

package websocket;

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

import javax.websocket.OnMessage;

import javax.websocket.OnOpen;

import javax.websocket.Session;

import javax.websocket.server.ServerEndpoint;

import org.json.JSONException;


@ServerEndpoint("/chatroomServerEndPoint")

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());
}


@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);
ChatroomServerEndPoint.sockets.put(this.myUniqueId, this);
System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"+sockets);
}


@OnMessage
public void handleMessage(String message, Session userSession) throws IOException, JSONException{
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;
}

}

enter code here

default.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<script type="text/javascript">

var jsonforlogout;

//alert("########################");

var websocket =new
WebSocket("ws://172.16.1.31:8080/ChatWebProject1/chatroomServerEndPoint");

//alert("$$$$$$$$$$$$$$$$$$$");

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) messagesTextArea.value += jsonData.message +"\n";
/* if(jsonData.message=='close'){websocket.close();} */
if(jsonData.users!=null)
{
var usercombo = document.getElementById("usercombo"); //combo
usercombo.length = 0;

usersTextArea.value="";
var i=0;
while(i<jsonData.users.length)
{
usersTextArea.value += jsonData.users[i] + "\n";
//combo
var comboitem = document.createElement("option");
comboitem.text = jsonData.users[i];//"utsav";//
comboitem.value = jsonData.users[i];//"10";
usercombo.options.add(comboitem);
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() {
//alert(messageText.value+ " h1");
websocket.send(messageText.value);
messageText.value="";
}
window.onbeforeunload = function () {
websocket.onclose = function() {};
websocket.close();
};

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

</script>
<title>Insert title here</title>
</head>
<body>
<div align= "center" style="color:orange;font-size: 8mm;">
WebChat Server
</div>
<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>
<br>
<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();"> -->
&nbsp;&nbsp;&nbsp;&nbsp;
To:<select id="usercombo" name="usercombo" >
</select>
</div>
</body>
</html>

Answer

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 = "";


@OnOpen
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());
        sessions.add(session);
}

@OnMessage
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();
    this.to = 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(this.to).equals(s.getId())) {
                System.out.print("True");
                Campusian c = new Campusian();
                c.setMessage(this.message);

                //Send message in Gson as string
                s.getBasicRemote().sendText(gson.toJson(c));
                break;
            }
        }

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

@OnClose
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) {
   this.to = to;
 }
 public String getTo() {
  return this.to;
 }
public void setFrom(String from) {
   this.from = from;
 }
 public String getFrom() {
  return this.from;
 }
}