简体   繁体   English

从java web socket读取的Javascript客户端

[英]Javascript client reading from java web socket

I have a Java websocket that keeps sending a bunch of coordinates which I want to CONSTANTLY intercept from a js client. 我有一个Java websocket,它不断发送一堆我想要从js客户端持续拦截的坐标。 Here is a simplified version of the java code: 这是java代码的简化版本:

public static void main(String args[]) throws IOException {
    final int portNumber = 2500;
    System.out.println("Creating server socket on port " + portNumber);
    ServerSocket serverSocket = new ServerSocket(portNumber);

    while (true) {
        Socket socket = serverSocket.accept();
        OutputStream os = socket.getOutputStream();
        PrintWriter pw = new PrintWriter(os, true);

        pw.println("test");
        pw.println("\r");

    }
    //later on close connection
    pw.close();
    socket.close();
}

As for my js code here is how it looks like: 至于我的js代码,它的外观如下:

var connection; 
   try{
         connection = new MozWebSocket('ws://localhost:2500/');
   }catch(e){
         connection = new WebSocket('ws://localhost:2500/');
   }
connection.onopen = function () {console.log('opened');};

connection.onclose = function(evt) { console.log("closed"); };
connection.onmessage = function(evt) { console.log("message"); };
connection.onerror = function(evt) { console.log(evt); };

After running this I get something like " Error during WebSocket handshake: No response code found in status line " and I understand that it's a difficult problem to overcome from a javascript client. 运行之后,我得到类似“ WebSocket握手期间的错误:在状态行中找不到响应代码 ”,我明白这是一个从javascript客户端克服的难题。 Thus I'm wondering if I should rearrange the way I implemented the websocket or should I make a websocket server instead? 因此,我想知道是否应该重新安排我实现websocket的方式,还是应该改为使用websocket服务器? But I am not sure if it will still allow me to constantly read the data my socket will be broadcasting at ALL TIMES. 但我不确定它是否仍然允许我不断读取我的套接字将在任何时候播放的数据。 Thank you in advance. 先感谢您。

You realize that websockets is a protocol right? 你意识到websockets是一个协议吗? It is not just sending plaintext. 它不只是发送明文。

I made an open source java webserver called Bowser that supports websockets. 我创建了一个名为Bowser的开源java webserver,它支持websockets。 You can take a look at some of the code here for inspiration or just use the library: https://github.com/mirraj2/Bowser/tree/master/src/bowser/websocket 您可以在这里查看一些代码以获取灵感,或者只使用库: https//github.com/mirraj2/Bowser/tree/master/src/bowser/websocket

To start a websocket server, it is as simple as: 要启动websocket服务器,它很简单:

int port = 12345;
 new WebSocketServer(port).onOpen(socket->{
   System.out.println("Client connected: " + socket);
 }).start();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM