java - 关于 websocket 的说明

标签 java tomcat websocket

我现在正在研究 Websocket。我需要一些说明。我正在将 websocket 与 tomcat 一起使用。

tomcat 如何将 websocket 请求映射到特定的 java 类。例如,我们可以在 web.xml 中给出 servlet 类。但是它如何用于 websocket?

最佳答案

1- Javascript : 为 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){ 

    }
}

关于java - 关于 websocket 的说明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40177260/

相关文章:

java - 使用选择排序对数组值进行排序时不期望输出

node.js - 使用 NodeJS 和 SocketIO 通过 Websockets 提供图像

java - Jetty WebsocketClient 不连接 Android 上的 SSL

java - 无法在 Tomcat 7 上部署 YouTrack (org.apache.catalina.LifecycleException)

Python 多线程与共享变量

java - Selenium - 尝试使用 "contains"通过其内容来定位表格单元格

java - 如何使用 Java 处理 Selenium 中的维基百科下拉列表

java - Java中如何使字体适合像素大小?如何将像素转换为点?

java - Tomcat JDBC 池连接全部卡在Socket Read,没有创建新连接

java - 从 Tomcat 7 迁移到 Tomcat 9 后的 "Too many open files"