java websocket gets the user sessionid and sends a message to the specified user

First write a json that contains your username or id and the username or id of the sender

var cmd = {
        "me":"2",
        "main":"woshi2",
        "to":"1"
      
  };

Then in the server websocket

@OnMessage
            public void mingzi(Session session,String mingzi){}

Since the accepted value is json, you need to write a class to accept

package bean;

public class me {
private String me;
private String main;
private String to;

public String getMain() {
	return x;
}
public void setMain(String main) {
	this.main = main;
}
public String getMe(){
	return Me;
}
public void setMe(String Me){
	this.me=me;
}

public String getTo(){
	return to;
}
public void setTo(String to){
	this.to=to;
}
}

In order to match the user sessionid with the name, use map to save the session and name with the key value

private static Map<String,Session> map=new HashMap<String,Session>();
	map.put(m.getZiji(), session);

Create a new session to send data to the client. Here is the name of the recipient passed by the client. Take the user session corresponding to her from the map.

Session to=map.get(m.getTo());

Then send your information to the recipient

to.getBasicRemote().sendText(m.getX());

Guess you like

Origin blog.csdn.net/weixin_40938312/article/details/104816000