我对websocket编程知之甚少但不知何故通过观看youtube我做了一个基本上是群聊的聊天应用程序,但现在我想与特定用户聊天而不是与整个群组聊天。我知道我必须为每个人生成一个独特的ID,但我现在如何连接到另一个请帮助并告诉我有关我必须下载的API?
这是我的代码
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();"> -->
To:<select id="usercombo" name="usercombo" >
</select>
</div>
</body>
</html>