无法从Web Socket向Java Scoket发送任何数据

时间:2016-04-15 17:26:51

标签: javascript java sockets websocket

Java代码我制作跨平台并需要使用javascript打开套接字从智能手表发送到计算机我需要发送数据的帮助 我打开了连接,但可以发送任何数据

   public class ChatSocketServer {
    private ServerSocket severSocket = null;
    private Socket socket = null;
    private InputStream inStream = null;
    private OutputStream outStream = null;

    public ChatSocketServer() {

    }

    public void createSocket() {
        try {
            ServerSocket serverSocket = new ServerSocket(3339);
            while (true) {
                socket = serverSocket.accept();
                inStream = socket.getInputStream();
                outStream = socket.getOutputStream();
                System.out.println("Connected");
                createReadThread();
                createWriteThread();

            }
        } catch (IOException io) {
            io.printStackTrace();
        }
    }

    public void createReadThread() {
        Thread readThread = new Thread() {
            public void run() {
                while (socket.isConnected()) {
                    try {
                        byte[] readBuffer = new byte[200];
                        int num = inStream.read(readBuffer);
                        if (num > 0) {
                            byte[] arrayBytes = new byte[num];
                            System.arraycopy(readBuffer, 0, arrayBytes, 0, num);
                            String recvedMessage = new String(arrayBytes, "UTF-8");
                            System.out.println("Received message :" + recvedMessage);
                        } else {
                            notify();
                        }
                        ;
                        //System.arraycopy();

                    } catch (SocketException se) {
                        System.exit(0);


                    } catch (IOException i) {
                        i.printStackTrace();
                    }


                }
            }
        };
        readThread.setPriority(Thread.MAX_PRIORITY);
        readThread.start();
    }

    public void createWriteThread() {
        Thread writeThread = new Thread() {
            public void run() {

                while (socket.isConnected()) {
                    try {
                        BufferedReader inputReader = new BufferedReader(new InputStreamReader(System.in));
                        sleep(100);
                        String typedMessage = inputReader.readLine();
                        if (typedMessage != null && typedMessage.length() > 0) {
                            synchronized (socket) {
                                outStream.write(typedMessage.getBytes("UTF-8"));
                                sleep(100);
                            }
                        }/* else {
                           notify();
                       }*/
                        ;
                        //System.arraycopy();

                    } catch (IOException i) {
                        i.printStackTrace();
                    } catch (InterruptedException ie) {
                        ie.printStackTrace();
                    }


                }
            }
        };
        writeThread.setPriority(Thread.MAX_PRIORITY);
        writeThread.start();

    }

    public static void main(String[] args) {
        ChatSocketServer chatServer = new ChatSocketServer();
        chatServer.createSocket();

    }
}

我使用的Javascript代码可能使用javascript和html5

   function PowerPowintSend() {

var webSocket = new WrapperWS();
webSocket.send("asdasdasdasd");

}

function WrapperWS() {
    if ("WebSocket" in window) {
        var ws = new WebSocket('ws://localhost:3339');
        var self = this;

        ws.onopen = function () {
            console.log("Opening a connection...");
            window.identified = false;
        };
        ws.onclose = function (evt) {
            console.log("I'm sorry. Bye!");
        };
        ws.onmessage = function (evt) {
             console.log(evt);
        };
        ws.onerror = function (evt) {
            console.log("ERR: " + evt.data);
        };

        this.write = function () {
            if (!window.identified) {
                connection.ident();
                console.debug("Wasn't identified earlier. It is now.");
            }
            ws.send(theText.value);
        };

        this.send = function (message, callback) {
            this.waitForConnection(function () {    
                ws.send(message);
                if (typeof callback !== 'undefined') {
                  callback();
                }
            }, 1000);
        };

        this.waitForConnection = function (callback, interval) {
            if (ws.readyState === 1) {
                callback();
            } else {
                var that = this;
                // optional: implement backoff for interval here
                setTimeout(function () {
                    that.waitForConnection(callback, interval);
                }, interval);
            }
        };

        this.ident = function () {
            var session = "Test";
            try {
                ws.send(session);
            } catch (error) {
                if (error instanceof InvalidStateError) {
                    // possibly still 'CONNECTING'
                    if (ws.readyState !== 1) {
                        var waitSend = setInterval(ws.send(session), 1000);
                    }
                }
            }
        window.identified = true;
            theText.value = "Hello!";
            say.click();
            theText.disabled = false;
        };

    };

}

2 个答案:

答案 0 :(得分:0)

webSocket连接不是通用套接字连接。它运行在TCP套接字上,但是它通过HTTP连接,然后升级到webSocket协议,包括交换一些安全凭证,然后它说出具有特定webSocket数据包格式的特定webSocket协议。

因此,您无法在浏览器的webSocket和Java中的普通套接字服务器之间进行通信。相反,您需要Java端的webSocket服务器。您需要一台知道如何说出webSocket连接顺序和协议的服务器。 Java中有许多webSocket服务器实现。这里是onethis post中提到了几个。我可能会看到使用Jetty的人最多的引用,但我不是Java高手,所以我没有具体的推荐。

为了让您了解webSocket协议的工作原理,您可以看到Writing WebSocket Servers

此外,这可能有助于解释:What's the difference between WebSocket and plain socket communication?

答案 1 :(得分:-1)

使用javacript打开Webscoket时,它会发送类似的数据

Connected
Received message :GET / HTTP/1.1
Host: localhost:3339
Connection: Upgrade
Pragma: no-cache
Cache-Control: no-cache
Upgrade: websocket
Origin: file://
Sec-WebSocket-Version: 13
User-Agent: Mozilla/5.0 (Windows N
Received message :T 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8,ar;q=0.6
Sec-WebSocket-Key: 1udKsf4w0jKj
Received message :OC0/0uIwFQ==
Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits