我现在正在探索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){
}
}