【发布时间】:2016-10-21 12:56:07
【问题描述】:
我现在正在探索 Websocket。我需要一些澄清。我正在将 websocket 与 tomcat 一起使用。
tomcat 如何将 websocket 请求映射到特定的 java 类。例如,我们可以在 web.xml 中给出 servlet 类。但是 websocket 是如何工作的呢?
【问题讨论】:
我现在正在探索 Websocket。我需要一些澄清。我正在将 websocket 与 tomcat 一起使用。
tomcat 如何将 websocket 请求映射到特定的 java 类。例如,我们可以在 web.xml 中给出 servlet 类。但是 websocket 是如何工作的呢?
【问题讨论】:
1- Javascript: 为 websocket 声明变量如下: var websocket; var address = "ws://localhost:8080/appName/MyServ";
注意 appName 是您的应用程序名称,而 MyServ 是端点
还在你的脚本中添加一个函数来打开连接:
var websocket;
var address = "ws://localhost:8080/appName/MyServ";
function openWS() {
websocket = new WebSocket(address);
websocket.onopen = function(evt) {
onOpen(evt)
};
websocket.onmessage = function(evt) {
onMessage(evt)
};
websocket.onerror = function(evt) {
onError(evt)
};
websocket.onclose = function(evt) {
onClose(evt)
};
}
function onOpen(evt) {
// what will happen after opening the websocket
}
function onClose(evt) {
alert("closed")
}
function onMessage(evt) {
// what do you want to do when the client receive the message?
alert(evt.data);
}
function onError(evt) {
alert("err!")
}
function SendIt(message) {
// call this function to send a msg
websocket.send(message);
}
2- 在服务器端,您需要一个 ServerEndpoint :我在上面的脚本中将其称为 myServ。
现在,我认为这正是您所需要的:
通过使用 @ServerEndpoint 注释来声明任何 Java POJO 类 WebSocket 服务器端点
import java.io.IOException
import javax.servlet.ServletContext;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
@ServerEndpoint(value="/MyServ")
public class MyServ{
@OnMessage
public void onMessage(Session session, String msg) throws IOException {
// todo when client send msg
// tell the client that you received the message!
try {
session.getBasicRemote().sendText("I got your message :"+ msg);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@OnOpen
public void onOpen (Session session) {
// tell the client the connection is open!
try {
session.getBasicRemote().sendText("it is open!");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@OnClose
public void onClose (Session session) {
System.out.println("websocket closed");
}
@OnError
public void onError (Session session){
}
}
【讨论】: