Java WebSocket库:https://github.com/TooTallNate/Java-WebSocket

Posted 布伊什

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java WebSocket库:https://github.com/TooTallNate/Java-WebSocket相关的知识,希望对你有一定的参考价值。

https://github.com/TooTallNate/Java-WebSocket

以下是简单示例:

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import static java.lang.System.err;
import static java.lang.System.out;
import java.net.InetSocketAddress;
import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;

public class Main {

    private static class WebScoketServerImpl extends WebSocketServer {

        private WebScoketServerImpl(int port) {
            super(new InetSocketAddress(port));
        }

        @Override
        public void onOpen(WebSocket conn, ClientHandshake handshake) {
            out.println("WebScoketServerImpl.onOpen(WebSocket, ClientHandshake) called");
        }

        @Override
        public void onClose(WebSocket conn, int code, String reason, boolean remote) {
            out.println("WebScoketServerImpl.onClose(WebSocket, int, String, boolean) called: " + reason);
        }

        @Override
        public void onMessage(WebSocket conn, String message) {
            out.println("WebScoketServerImpl.onMessage(WebSocket, String) called: " + message);
            JsonObject root = new JsonParser().parse(message).getAsJsonObject();
            if (root.get("type").getAsString().equals("print")) {
                JsonObject jsonObject = new JsonObject();
                jsonObject.addProperty("type", "print");
                jsonObject.addProperty("error_message", "None");
                jsonObject.addProperty("error_code", 1);
                conn.send(jsonObject.toString());
            } else {
                JsonObject jsonObject = new JsonObject();
                jsonObject.addProperty("type", "getWeight");
                jsonObject.addProperty("error_code", 0);
                jsonObject.addProperty("weight", "0.000kg");
                conn.send(jsonObject.toString());
            }
        }

        @Override
        public void onError(WebSocket conn, Exception ex) {
            err.println("WebScoketServerImpl.onError(WebSocket, Exception) called: " + ex);
        }

        @Override
        public void onStart() {
            out.println("WebScoketServerImpl.onStart() called");
        }

    }

    public static void main(String[] args) {
        Main.WebScoketServerImpl websocketServer = new Main.WebScoketServerImpl(1234);
        websocketServer.start();
    }
}

 

以上是关于Java WebSocket库:https://github.com/TooTallNate/Java-WebSocket的主要内容,如果未能解决你的问题,请参考以下文章

在 HTTPS 页面上创建 websocket 对象时,如何阻止 chrome 将 websocket 从 WS 升级到 WSS

JAVA 中的 WebSocket SSL

Java SE上的Websocket?

带代理的 Java websocket

python爬虫 请教一下,python怎么连接websocket

WebSocket 在 Internet Explorer 下关闭 - 错误代码 1006