套接字服务器无法与JavaScript套接字客户端

时间:2016-08-03 15:22:35

标签: javascript java sockets websocket socket.io

以下是socket的代码。

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Random;

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("Server 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("server received :" + 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 {
                        while(true){
                            synchronized (socket) {
                                Random random = new Random();
                                int i = random.nextInt(100);
                                outStream.write(Integer.toString(i).getBytes("UTF-8"));
                                sleep(100);
                            }
                        }/*
                        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) {
        System.out.println("char socket server got started");
        ChatSocketServer chatServer = new ChatSocketServer();
        chatServer.createSocket();

    }
}

当我尝试连接Java套接字客户端时,上面的代码工作正常。我不确定为什么在连接JavaScript时会抛出错误。

的JavaScript

try{
    var host = "ws://localhost:3339/";
    var socket = new WebSocket(host);
    console.log(socket.readyState);
    socket.onopen = function(){
        console.log(socket.readyState);
    };
        socket.onmessage = function(msg){
            console.log(msg.data);
        };
        socket.onclose = function(){
            console.log(socket.readyState);
        };          
        socket.onerror = function(error) {
            // connection failed - try polling
            console.log(socket.readyState);
        };

    } catch(exception){
        console.log(exception);
    }

当我尝试从JavaScript读取值时,会抛出以下错误:

  

与'ws:// localhost:3339 /'的WebSocket连接失败:WebSocket握手期间出错:状态行无效

但我可以使用Java代码在服务器和客户端之间进行同步。

1 个答案:

答案 0 :(得分:2)

webSocket连接需要特定的webSocket服务器,而不仅仅是普通的TCP服务器。当浏览器使用webSocket连接时,它具有特定的连接顺序(以HTTP请求开始,然后升级到webSocket连接),并且它具有特定的安全方案,并且具有用于发送数据的特定数据格式。服务器必须支持所有这些,以便正确地接受来自浏览器的webSocket连接并与之通信。

关于invalid handshake的错误只是表示浏览器尝试连接,但服务器没有为webSocket协议提供正确的响应。

由于您的服务器看起来像是Java,因此Java有许多webSocket服务器实现。您应该抓住其中一个并使用它,而不是自己实现整个webSocket连接方案和协议。

您可能会发现本文有用:

How to build Java WebSocket Applications Using the JSR 356 API

以下是关于Java的其他webSocket库的答案(或许有点过时):

WebSockets production ready server in Java?