套接字服务器未与JavaScript套接字客户端连接



下面是套接字的代码。

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代码在服务器和客户端之间进行同步。

webSocket连接需要一个特定的webSocket服务器,而不仅仅是一个普通的TCP服务器。当浏览器使用webSocket进行连接时,它有一个特定的连接序列(从HTTP请求开始,然后升级为webSocket连接),它有特定的安全方案,它有用于发送数据的特定数据格式。服务器必须支持所有这些,才能正确接受浏览器的webSocket连接并与之通信。

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

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

你可能会发现这篇文章很有帮助:

如何使用JSR 356 API 构建Java WebSocket应用程序

这里有一个关于Java的其他webSocket库的答案(可能有点过时):

Java中的WebSockets生产就绪服务器?

相关内容

  • 没有找到相关文章

最新更新