简体   繁体   中英

Socket server not connect with JavaScript socket client

Below is the code for 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();

    }
}

The above code is working fine when I try to connect with Java socket client. Am not sure why it throwing error when connect with 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);
    }

When I try to read the value from JavaScript, it throws the following error:

WebSocket connection to 'ws://localhost:3339/' failed: Error during WebSocket handshake: Invalid status line

But I can able to sync up between server and client by using Java code.

A webSocket connection requires a specific webSocket server, not just a plain TCP server. When a browser connects using a webSocket, it has a specific connection sequence (that starts with an HTTP request that is then upgraded to a webSocket connection) and it has a specific security scheme and it has a specific data format for sending data. The server must support all that in order to properly accept and communicate with a webSocket connection from a browser.

The error about an invalid handshake is just an indication that the browser tried to connect, but the server didn't provide the right response for the webSocket protocol.

Since it looks like your server is in Java, there are numerous webSocket server implementations for Java. You should probably grab one of those and use it rather than implementation the whole webSocket connection scheme and protocol yourself.

You may find this article helpful:

How to build Java WebSocket Applications Using the JSR 356 API

And here's an answer (a little dated perhaps) about other webSocket libraries for Java:

WebSockets production ready server in Java?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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