在Java中创建WebSocket服务器

时间:2019-06-03 16:39:56

标签: java websocket

我需要创建简单的WebSocket客户端,该客户端发送来回Json消息。

我创建了可以握手的服务:

public class WebSocket {

        public static void main(String[] args) throws IOException, NoSuchAlgorithmException {
            ServerSocket server = new ServerSocket(3703);
            try {
                System.out.println("Server has started on 127.0.0.1:3703.\r\nWaiting for a connection...");
                Socket client = server.accept();
                System.out.println("A client connected.");

                InputStream in = client.getInputStream();
                OutputStream out = client.getOutputStream();
                Scanner s = new Scanner(in, "UTF-8");

                try {
                    String data = s.useDelimiter("\\r\\n\\r\\n").next();
                    System.out.println(data);
                    Matcher get = Pattern.compile("GET").matcher(data);

                    if (get.find()) {
                        System.out.println("found");
                        Matcher match = Pattern.compile("Sec-WebSocket-Key: (.*)").matcher(data);
                        match.find();
                        byte[] response = ("HTTP/1.1 101 Switching Protocols\r\n"
                                + "Connection: Upgrade\r\n"
                                + "Upgrade: websocket\r\n"
                                + "Sec-WebSocket-Accept: "
                                + Base64.getEncoder().encodeToString(MessageDigest.getInstance("SHA-1").digest((match.group(1) + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").getBytes("UTF-8")))
                                + "\r\n\r\n").getBytes("UTF-8");
                        out.write(response, 0, response.length);


//Code for reading and decoding messages



                    }
                } finally {
                    s.close();
                }
            } finally {
                server.close();
            }
        }
    }

但是实现消息解码的最佳方法是什么?我可以为此目的使用任何库吗?

一般来说,创建WebSocket服务的最佳方法是什么?我应该使用应用程序服务器还是可以创建独立服务。在独立服务的情况下应该使用哪些库?

0 个答案:

没有答案