Java服务器JavaScript客户端WebSockets [英] Java server JavaScript client WebSockets

查看:141
本文介绍了Java服务器JavaScript客户端WebSockets的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Java服务器和JavaScript客户端之间建立连接,但我在客户端遇到此错误:

I'm trying to do a connection between a server in Java and a JavaScript client but I'm getting this error on client side:


与'ws://127.0.0.1:4444 /'的WebSocket连接失败:在收到握手响应之前连接已关闭

它可能保持OPENNING状态,因为从不调用 connection.onopen 函数。 console.log('已连接!')未被调用。

It maybe stays on OPENNING state because the connection.onopen function is never called. The console.log('Connected!') isn't being called.

有人能让我知道是什么这里出错了吗?

Could someone let me know what is going wrong here?

服务器

import java.io.IOException;
import java.net.ServerSocket;

public class Server {

    public static void main(String[] args) throws IOException {

        try (ServerSocket serverSocket = new ServerSocket(4444)) {
            GameProtocol gp = new GameProtocol();

            ServerThread player= new ServerThread(serverSocket.accept(), gp);
            player.start();

        } catch (IOException e) {
            System.out.println("Could not listen on port: 4444");
            System.exit(-1);
        }

    }

}

ServerThread

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class ServerThread extends Thread{

    private Socket socket = null;
    private GameProtocol gp;

    public ServerThread(Socket socket, GameProtocol gp) {
        super("ServerThread");
        this.socket = socket;
        this.gp = gp;
    }

    public void run() {

        try (
                PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
                BufferedReader in = new BufferedReader(
                        new InputStreamReader(
                                socket.getInputStream()));
                ) {
            String inputLine, outputLine;

            while ((inputLine = in.readLine()) != null) {
                outputLine = gp.processInput(inputLine);
                System.out.println(outputLine);
            }
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

GameProtocol

public class GameProtocol {

    public String processInput(String theInput) {

        String theOutput = null;

        theOutput = theInput;

        return theOutput;
    }
}

客户

var connection = new WebSocket('ws://127.0.0.1:4444');

connection.onopen = function () {
    console.log('Connected!');
    connection.send('Ping'); // Send the message 'Ping' to the server
};

// Log errors
connection.onerror = function (error) {
    console.log('WebSocket Error ' + error);
};

// Log messages from the server
connection.onmessage = function (e) {
    console.log('Server: ' + e.data);
};


推荐答案

首先,您的代码看起来与Java完全相同和JavaScript一个。两者都适用于它们的设计,但事实是你正在尝试将WebSocket客户端连接到套接字服务器。

To start with, both your code looks identical the Java and JavaScript one. Both work for what they are design to, but the facts is that you are trying to connect a WebSocket client to a socket server.

我知道它们是两个不同的东西关于这个回答

As I know they are two different things regarding this answer.

我从未尝试过你的方式。如果我有一个使用套接字的网络应用程序而不是纯客户端/服务器套接字,如果它是一个Web应用程序,那么我也会使用WebSocket。

I have never tried it your way. That said if I have a network application that use socket than it would be pure client/server socket, and if it was a web application than I would use WebSocket on both side as well.

到目前为止一直很好..

为了完成这项工作,这个答案建议在服务器端使用任何可用的WebSocket,问题就解决了。

To make this work, this answer suggests to use any available WebSocket on server side and your problem is solved.

我正在使用 WebSocket for Java ,这是一个示例实现我已经使用您的客户端代码进行了测试,它在客户端和服务器端都有效。

I am using WebSocket for Java and here is a sample implementation that I have tested with your client code and it works, both on client and server side.

import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;

import java.net.InetSocketAddress;
import java.util.HashSet;
import java.util.Set;

public class WebsocketServer extends WebSocketServer {

    private static int TCP_PORT = 4444;

    private Set<WebSocket> conns;

    public WebsocketServer() {
        super(new InetSocketAddress(TCP_PORT));
        conns = new HashSet<>();
    }

    @Override
    public void onOpen(WebSocket conn, ClientHandshake handshake) {
        conns.add(conn);
        System.out.println("New connection from " + conn.getRemoteSocketAddress().getAddress().getHostAddress());
    }

    @Override
    public void onClose(WebSocket conn, int code, String reason, boolean remote) {
        conns.remove(conn);
        System.out.println("Closed connection to " + conn.getRemoteSocketAddress().getAddress().getHostAddress());
    }

    @Override
    public void onMessage(WebSocket conn, String message) {
        System.out.println("Message from client: " + message);
        for (WebSocket sock : conns) {
            sock.send(message);
        }
    }

    @Override
    public void onError(WebSocket conn, Exception ex) {
        //ex.printStackTrace();
        if (conn != null) {
            conns.remove(conn);
            // do some thing if required
        }
        System.out.println("ERROR from " + conn.getRemoteSocketAddress().getAddress().getHostAddress());
    }
}

在您的主要方法上:

new WebsocketServer().start();

您可能需要操纵您的代码以适应此实现,但这应该是工作。

You might need to manipulate your code to fit it with this implementation, but that should be part of the job.

以下是2次测试的测试输出:

Here is the test output with 2 tests:

New connection from 127.0.0.1
Message from client: Ping
Closed connection to 127.0.0.1
New connection from 127.0.0.1
Message from client: Ping






这里是WebSocket maven配置,否则手动下载JAR文件并导入它在您的IDE /开发环境中:


here is WebSocket maven configuration, otherwise download the JAR file/s manually and import it in your IDE/development environment:

<!-- https://mvnrepository.com/artifact/org.java-websocket/Java-WebSocket -->
<dependency>
    <groupId>org.java-websocket</groupId>
    <artifactId>Java-WebSocket</artifactId>
    <version>1.3.0</version>
</dependency>

链接到 WebSocket

这篇关于Java服务器JavaScript客户端WebSockets的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆