【发布时间】:2017-05-19 03:17:46
【问题描述】:
我正在尝试在 Java 中的服务器和 JavaScript 客户端之间建立连接,但我在客户端收到此错误:
与“ws://127.0.0.1:4444/”的 WebSocket 连接失败:在收到握手响应之前连接已关闭
它可能保持在 OPENNING 状态,因为从未调用过 connection.onopen 函数。 console.log('Connected!') 未被调用。
谁能告诉我这里出了什么问题?
服务器
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);
}
}
}
服务器线程
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();
}
}
}
游戏协议
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);
};
【问题讨论】:
-
我试过了,它工作得很好......你用什么浏览器进行测试?另外,是否有任何防火墙可以阻止/干扰响应?
-
我使用的是 Chrome 55。我不喜欢。另外,如果我在服务器端打印出响应,我会收到我在上面放置的消息。
-
似乎一切正常...也许,试试另一个端口?像 12000 或更高,我听说有些系统不喜欢低端口号...我只是推测,因为我不知道我们的设置之间可能有什么区别...
-
我已经尝试过您的建议,但问题仍然存在。您在 Chrome 中尝试过,但它没有打印 WebSocket 错误?
-
是的,我使用的是 chrome 版本 54.0.2840.71 m(64 位),我在 eclispe 中启动了我的服务器,当我用我的脚本加载页面时,服务器写道:“客户端已连接。”
标签: javascript java websocket java-websocket