我正在探索Websocket。我需要一些澄清。我正在使用带有tomcat的websocket。
如何将tomcat映射到特定java类的websocket请求。例如,我们可以在web.xml中提供servlet类。但它如何适用于websocket?
答案 0 :(得分:0)
1- Javascript: 声明websocket的变量如下: var websocket; var address =" ws:// localhost:8080 / appName / MyServ&#34 ;;
请注意appName是您的应用程序名称,MyServ是Endpoint
还在你的脚本中添加一个函数来打开连接:
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){
}
}