如何在Java中实现WebSocket服务器?

时间:2019-09-13 10:51:04

标签: java websocket server

我正在为通讯应用设置我的第一个websocket服务器。我似乎无法弄清楚如何用Java实现websocket。

我曾尝试过创建基于注释的端点,但未成功,但是我不确定客户端信息将通过哪里。基本上,这是我代码的要旨,而无需赘述。

我正在尝试让MessageHelper类处理websocket信息传输,我只是不知道如何实际进行传输。

class MainServer implements Runnable {
// VARIABLES
    ServerSocket serverSocket = null;
    int port;
// CONSTRUCTORS
    MainServer(int p) {
        this.port = p;
    }
// METHODS
    public void run() {
        openServerSocket();
        while(!isStopped()){
            try{
                clientSocket = serverSocket.accept();
            } catch(IOException e) {
                // Do something
            }
            new Thread(new MainThread(clientSocket)).start();
        }
    }
}

// Other methods below.
public class MainThread {

    final Socket socket;


    MainThread(Socket s) {
        this.socket = s;
    }

    public void run() {
        try{
            BufferedReader br = new BufferedReader(
                new InputStreamReader(socket.getInputStream()));

            String input = br.readLine(), read = br.readLine();
            while(!input.isEmpty()) {
                read += "\n";
                read += input;
                input = br.readLine();
            }

            /**
            *  Everything works fine, I'm just not sure where to go
            * from here. I tried creating MessageHelper into the java
            * websocket implementation using annotations but it did not 
            * accept input from the client after the handshake was
            * made. My client would send something but it would just 
            * give and EOFException.
            **/
            if(websocketHandshakeRequest(read)) {
                MessageHelper messageHelper = 
                    new MessageHelper(this.socket);
            } else {
                // Do something
            }
        } catch(Exception e) {
            // Do something.
        }
    }
}

2 个答案:

答案 0 :(得分:1)

如果您愿意使用Java Spring(我认为这对您的用例非常有用),则设置websocket服务器和客户端连接非常容易。

这里有一个例子-https://spring.io/guides/gs/messaging-stomp-websocket/

答案 1 :(得分:1)

不要混淆WebSocket的名称。 TCP套接字和WebSocket是完全不同的“套接字”。

在Java中,您将ServerSocket用于TCP套接字。 TCP是一种传输层协议,用于实现POP3和HTTP等应用层协议。

WebSocket是HTTP / 1.1协议升级,通常在Web服务器和Web浏览器中使用。您不能将ServerSocket用于WebSocket协议,至少不能像您想象的那样直接。首先,您必须实现HTTP / 1.1协议,然后实现WebSocket协议。

在Java世界中,您可以使用诸如Tomcat或Jetty之类的Web服务器,它们提供WebSocket实现和high level Java API。该API是Jave Enterprise Edition(JEE)的一部分。另请参见Jave EE 7 Tutorial - Chapter 18 Java API for WebSocket

例如Jetty是一种轻量级的JEE Web服务器,可以嵌入到您的应用程序中或作为独立服务器运行。参见Jetty Development Guide - Chapter 26. WebSocket Introduction

因此,在运行了支持WebSocket的JEE Web服务器(如Jetty)中运行的Java Web应用程序中,您可以按以下方式实现服务器端WebSocket:

package com.example.websocket;

import org.apache.log4j.Logger;

import javax.websocket.CloseReason;
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;
import java.io.IOException;

@ServerEndpoint("/toUpper")
public class ToUpperWebsocket {

  private static final Logger LOGGER = Logger.getLogger(ToUpperWebsocket.class);

  @OnOpen
  public void onOpen(Session session) {
    LOGGER.debug(String.format("WebSocket opened: %s", session.getId()));
  }

  @OnMessage
  public void onMessage(String txt, Session session) throws IOException {
    LOGGER.debug(String.format("Message received: %s", txt));
    session.getBasicRemote().sendText(txt.toUpperCase());
  }

  @OnClose
  public void onClose(CloseReason reason, Session session) {
    LOGGER.debug(String.format("Closing a WebSocket (%s) due to %s", session.getId(), reason.getReasonPhrase()));
  }

  @OnError
  public void onError(Session session, Throwable t) {
    LOGGER.error(String.format("Error in WebSocket session %s%n", session == null ? "null" : session.getId()), t);
  }
}

您可以使用@ServerEndpoint批注将类注册为特定路径的WebSocket处理程序。然后,用于HTTPS连接的WebSocket URL为ws://host:port/context/toUpperwss://host:port/context/toUpper

编辑: 这是一个非常简单的HTML页面,用于演示与上述WebSocket的客户端连接。该页面由与WebSocket相同的Web服务器提供。包含WebSocket的Web应用程序部署在本地主机端口7777的上下文“ websocket”上。

    <html>
    <body>
    <h2>WebSocket Test</h2>
    <div>
    <input type="text" id="input" />
    </div>
    <div>
    <input type="button" id="connectBtn" value="CONNECT" onclick="connect()" />
    <input type="button" id="sendBtn" value="SEND" onclick="send()" disable="true" />
    </div>
    <div id="output">
    <h2>Output</h2>
    </div>
    </body>
    <script type="text/javascript">
    var webSocket;
    var output = document.getElementById("output");
    var connectBtn = document.getElementById("connectBtn");
    var sendBtn = document.getElementById("sendBtn");
    var wsUrl = (location.protocol == "https:" ? "wss://" : "ws://") + location.hostname + (location.port ? ':'+location.port: '') + "/websocket/toUpper";

    function connect() {
      // open the connection if one does not exist
      if (webSocket !== undefined
        && webSocket.readyState !== WebSocket.CLOSED) {
        return;
      }

      updateOutput("Trying to establish a WebSocket connection to <code>" + wsUrl + "</code>");

      // Create a websocket
      webSocket = new WebSocket(wsUrl);

      webSocket.onopen = function(event) {
        updateOutput("Connected!");
        connectBtn.disabled = true;
        sendBtn.disabled = false;
      };

      webSocket.onmessage = function(event) {
        updateOutput(event.data);
      };

      webSocket.onclose = function(event) {
        updateOutput("Connection Closed");
        connectBtn.disabled = false;
        sendBtn.disabled = true;
      };
    }

    function send() {
      var text = document.getElementById("input").value;
      webSocket.send(text);
    }

    function closeSocket() {
      webSocket.close();
    }

    function updateOutput(text) {
      output.innerHTML += "<br/>" + text;
    }
    </script>
    </html>

Sample WebSocket webpage rendered in Firefox