我正在尝试在java中编写一个Web套接字服务器,独立一个,没有tomcat,glassfish等。客户端是用javascript编写的,但问题在于我认为服务器端,这里是代码:
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket();
server.bind(new InetSocketAddress("localhost", 1234));
System.out.println("Listening for connection on port 1234...");
while (true) {
try {
Socket socket = server.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//PrintWriter out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
while(true) {
String msg = in.readLine();
if(msg != null) {
System.out.println(msg);
}
}
} catch(Exception e) {
e.printStackTrace();
}
}
}
}
这是javascript客户端只是为了完成的目的:
$(window).load(function() {
var port = 1234
var ws = new WebSocket("ws://localhost:"+ port);
ws.onopen = function(e) {
console.log("open");
//ws.send("Message to send");
//console.log("Message is sent...");
};
ws.onmessage = function (e) {
var msg = e.data;
console.log("received: " + msg);
};
ws.onclose = function() {
console.log("closed");
};
// Connection opened
ws.addEventListener('open', function (event) {
ws.send('Hello Server!');
});
// Listen for messages
ws.addEventListener('message', function (event) {
ws.log('Message from server ', event.data);
});
$("#send-btn").click(function() {
var msg = $("#message").val()
console.log(ws);
console.log("sending: " + msg);
ws.send(msg)
});
});
现在,只要我想将消息发送到服务器(点击事件),我就会得到这样的结果:
Uncaught DOMException: Failed to execute 'send' on 'WebSocket': Still in CONNECTING state.
顺便建立连接时,我在服务器的控制台上获得以下信息:
GET / HTTP/1.1
Host: localhost:1234
Connection: Upgrade
Pragma: no-cache
Cache-Control: no-cache
Upgrade: websocket
Origin: file://
Sec-WebSocket-Version: 13
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.8,pl;q=0.6,fr;q=0.4
Sec-WebSocket-Key: 4xjnNYP9k7AUyXFU5LO42g==
Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits
网上有这么多服务器,我做错了什么?我的猜测是握手可能出现问题,但我无法找到任何修复它的东西。谢谢你的帮助!