我正在使用WebSocket在Javascript客户端和Java Server之间进行双向通信,这是我的项目层次结构。
我创建了一个javascript客户端 websocket.js
var webSocket;
var messages = document.getElementById("messages");
function openSocket()
{
if(webSocket !== undefined && webSocket.readyState !== WebSocket.CLOSED)
{
writeResponse("WebSocket is already opened.");
return;
}
webSocket = new WebSocket("ws://localhost:8181/TeenPattiWebRCF/echo");
webSocket.onopen = function(event)
{
if(event.data === undefined)
return;
writeResponse(event.data);
};
webSocket.onmessage = function(event){
writeResponse(event.data);
};
webSocket.onclose = function(event){
alert("Connection closed "+event.data);
writeResponse("Connection closed");
};
}
function send(){
var text = document.getElementById("messageinput").value;
webSocket.send(text);
}
function closeSocket(){
webSocket.close();
}
function writeResponse(text){
messages.innerHTML +="<br/>"+text;
}
这是我的Java服务器
@ServerEndpoint("/echo")
public class EchoServer
{
@OnOpen
public void onOpen(Session session)
{
System.out.println(session.getId() + " has opened a connection");
try
{
session.getBasicRemote().sendText("Connection Established");
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
@OnMessage
public void onMessage(String message, Session session)
{
for(Session singleSession : session.getOpenSessions()){
singleSession.getBasicRemote().sendText("Hello");
}
}
@OnClose
public void onClose(Session session){
System.out.println("Session " +session.getId()+" has ended");
}
}
我有index.jsp,我在onload上调用websocket.js的openSocket()函数。
我正在使用HTTP / 1.1端口号8181在Tomcat上运行我的项目。
但是在服务器和客户端之间没有建立连接并且显示连接已关闭
1.实例化时有什么不对
webSocket = new WebSocket(“ws:// localhost:8181 / TeenPattiWebRCF / echo”); ?
显示Ready State = 3的调试器
2.如果我在具有相同通道名称的两个不同包中有两个不同的ServerEndPoint(例如,@ ServerEndpoint(“/ echo”)),该怎么办?