我正在尝试学习网络套接字。我开发了一个聊天的Web应用程序,它在本地服务器上工作得很好,但在我的VPS上却没有。似乎我的网址“ws://”+ document.location.host +“/ TikTok / wschat”存在问题。如果有人能帮助我,请告诉我。我是学习者,请不要介意我的英语。我正在使用基于linux的vps与java 8和tomcat 7.提前感谢
与'ws://tiktokchat.tk:8084 / wschat'的WebSocket连接失败:错误 在连接建立:net :: ERR_CONNECTION_REFUSED
var ws=null;
var wsUri = "ws://" + document.location.host+"/TikTok/wschat";
console.log(wsUri);
ws = new WebSocket(wsUri);
ws.onmessage = function(message){
document.getElementById("chatlog").textContent += message.data + "\n";
};
function postToServer(name){
ws.send(name+">>>"+document.getElementById("groupMsg").value);
document.getElementById("groupMsg").value = "";
};
function closeConnect(){
ws.close();
};
<div id='groupchat'>
<textarea id="chatlog" readonly></textarea><br/>
<input id="groupMsg" type="text" />
<button type="submit" id="sendButton" onClick="postToServer('${username}')">Send!</button>
<button type="submit" id="sendButton" onClick="closeConnect()">End</button>
</div>
package com.tiktok.controller;
import java.io.IOException;
import java.util.ArrayList;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
@ServerEndpoint(value = "/wschat")
public class WsChat{
//notice:not thread-safe
private static ArrayList<Session> sessionList = new ArrayList<Session>();
@OnOpen
public void onOpen(Session session){
try{
sessionList.add(session);
//asynchronous communication
session.getBasicRemote().sendText("Welcome!");
}catch(IOException e){}
}
@OnClose
public void onClose(Session session){
System.out.println("close");
sessionList.remove(session);
}
@OnMessage
public void onMessage(String msg){
System.out.println("message");
try{
for(Session session : sessionList){
//asynchronous communication
session.getBasicRemote().sendText(msg);
}
}catch(IOException e){}
}
}