[英]Web Socket in Tomcat 7
I am new in web socket. 我是Web套接字的新手。 I had learned some tutorial to implement web socket.
我已经学习了一些实现Web套接字的教程。 But it is not working properly.
但是它不能正常工作。 I don't know what I have done wrongly.
我不知道我做错了什么。
note: I have not done any configuration (web.xml) and I have been used tomcat 7.0.47,jdk 1.6.0_24 注意:我尚未进行任何配置(web.xml),并且已使用过tomcat 7.0.47,jdk 1.6.0_24
This is My Server side code:
这是我的服务器端代码:
package com.hmkcode;
import java.io.IOException;
import java.util.LinkedList;
import javax.websocket.EncodeException;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
@ServerEndpoint(value="/websocket/{client-id}")
public class MyServerEndpoint {
private static final LinkedList<Session> clients = new LinkedList<Session>();
@OnOpen
public void onOpen(Session session) {
clients.add(session);
}
@OnMessage
public void onMessage(String message,@PathParam("client-id") String clientId) {
for (Session client : clients) {
try {
client.getBasicRemote().sendObject(clientId+": "+message);
} catch (IOException e) {
e.printStackTrace();
} catch (EncodeException e) {
e.printStackTrace();
}
}
}
@OnClose
public void onClose(Session peer) {
clients.remove(peer);
}
}
This is my Web client code
这是我的Web客户端代码
var URL = "ws://localhost:8080/WebSocket1/websocket/web-client";
var websocket;
$(document).ready(function(){
connect();
});
function connect(){
websocket = new WebSocket(URL);
websocket.onopen = function(evnt) { onOpen(evnt);};
websocket.onmessage = function(evnt) { onMessage(evnt); };
websocket.onerror = function(evnt) { onError(evnt); };
}
function sendMessage() {
websocket.send($("#message").val());
}
function onOpen() {
updateStatus("connected");
}
function onMessage(evnt) {
if (typeof evnt.data == "string") {
$("#received_messages").append(
$('<tr/>')
.append($('<td/>').text("1"))
.append($('<td/>').text(evnt.data.substring(0,evnt.data.indexOf(":"))))
.append($('<td/>').text(evnt.data.substring(evnt.data.indexOf(":")+1))));
}
}
function onError(evnt) {
alert('ERROR: ' + evnt.data);
}
function updateStatus(status){
if(status == "connected"){
$("#status").removeClass (function (index, css) {
return (css.match (/\blabel-\S+/g) || []).join(' ');
});
$("#status").text(status).addClass("label-success");
}
}
My guess is... 我的猜测是
Since you ServerEndpoint maps an argument "{client-id}" it should be present in the URL your client uses to connect. 由于ServerEndpoint映射参数“ {client-id}”,因此该参数应出现在客户端用于连接的URL中。
Either you remove the parameter on server-side or you need to include a value to it on client-side. 您可以在服务器端删除该参数,或者需要在客户端将其包含一个值。
Again, just guessing. 再次,只是猜测。 It would be useful if you include more information regarding the issue (eg, server logs)
如果您包含有关该问题的更多信息(例如,服务器日志),它将很有用。
[]s Heleno [] Heleno
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.