【发布时间】:2013-12-16 11:57:16
【问题描述】:
我正在通过 Web 套接字向 Java 服务器发送文本,但从未调用过 onpen 函数,这是用于客户端 (WebSocketTest) 的函数,当我关闭服务器时,onclose 函数的警报消息正确调用
function WebSocketTest()
{
if ("WebSocket" in window)
{
alert("WebSocket is supported by your Browser!");
// Let us open a web socket
var ws = new WebSocket("ws://localhost:4444");
ws.onopen = function()
{
// Web Socket is connected, send data using send()
ws.send("Message to send");
alert("Message is sent...");
};
ws.onmessage = function (evt)
{
var received_msg = evt.data;
alert("Message is received...");
};
ws.onclose = function()
{
// websocket is closed.
alert("Connection is closed...");
};
}
else
{
// The browser doesn't support WebSocket
alert("WebSocket NOT supported by your Browser!");
}
}
这是服务器收到的内容
GET / HTTP/1.1
Upgrade: websocket
Connection: Upgrade
Host: localhost:4444
Origin: null
Pragma: no-cache
Cache-Control: no-cache
Sec-WebSocket-Key: 4BAiV8AU80juonjYQw5V9g==
Sec-WebSocket-Version: 13
Sec-WebSocket-Extensions: x-webkit-deflate-frame
User-Agent: Mozilla/5.0 (Windows NT 6.2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36
这是服务器端
public class InvoiceListener {
private static BufferedReader in;
private final static int port = 4444;
private static ServerSocket listenSocket;
private static Socket client;
private static Invoice invoice;
private static String info;
public static void main(String[] args) throws IOException {
PrintInvoice printer;
ServerSocket listenSocket = new ServerSocket(port);
System.out.println("Listening");
client = listenSocket.accept();
System.out.println("client connected !");
in = new BufferedReader(new InputStreamReader(
client.getInputStream()));
while ((info = in.readLine()) != null) {
System.out.println(info);
}
}
}
【问题讨论】:
-
你使用的是什么网络服务器?
-
java,使用java ServerSocket
-
您测试的浏览器是什么?什么版本?
-
谷歌浏览器版本 31.0.1650.63 m
-
你能用更多代码更新你的帖子吗?我的意思是你是如何在服务器(java)上接收请求的,你什么时候在你的页面中调用这个函数?
标签: java javascript html websocket client