我正在尝试将PHP函数转换为jQuery函数,以便我可以直接从浏览器使用TCP/IP套接字本地连接。
我用这个:
$socket = @fsockopen('xxx.xxx.xxx.xxx', '8810', $err_no, $err_str);
if(!$socket){
return 'Errore #'.$err_no.': '.$err_str;
}else{
fwrite($socket, '["D";"C";"?ST";200]');
$read = fread($socket, 2024);
//other stuff...
return $read;
fclose($socket);
}
这很好。然后我从Google Code站点下载了Github jQuery Websocket 0.0.4,并遵循了示例,但没有成功。
我只是简单地尝试建立连接并以这种方式发送数据:
ws = $.websocket("ws://95.110.224.199:8810/");
ws.send('string', '["D";"C";"?ST";200]');
这给了我"undefined is not a function"的错误。
然后我试着看看连接是否真的建立(不发送数据):
var ws = $.websocket("ws://xxx.xxx.xxx.xxx:8810/", {
open: function() {console.log('WS:connesso')},
close: function() {console.log('WS:chiuso')},
});
我运气不好…控制台什么也没说……有什么提示或帮助吗?
也许您错过了jquery.websocket.js
文件,但您可以使用javascript web套接字:
ws = new WebSocket('ws://95.110.224.199:8810/');
或者你可以用0.0.0.0代替你的ip,因为有些服务器不允许直接访问ip:
ws = new WebSocket('ws://0.0.0.0:8810/')
ws.onopen = function(msg) {
// Logic for opened connection
console.log('Connection successfully opened');
};
ws.onmessage = function(msg) {
// Handle received data
};
ws.onclose = function(msg) {
// Logic for closed connection
console.log('Connection was closed.');
}
ws.error =function(err){
console.log(err); // Write errors to console
}
WebSockets不允许您以fsockopen
从PHP的方式连接到任意TCP服务器。服务器还必须支持WebSocket协议,特别是:
如果服务器选择接受传入的连接,它必须使用一个有效的HTTP响应进行应答,该响应指示以下内容。
1. A Status-Line with a 101 response code as per RFC 2616 [RFC2616]. Such a response could look like "HTTP/1.1 101 Switching Protocols". 2. An |Upgrade| header field with value "websocket" as per RFC 2616 [RFC2616]. 3. A |Connection| header field with value "Upgrade". 4. A |Sec-WebSocket-Accept| header field. The value of this header field is constructed by concatenating /key/, defined above in step 4 in Section 4.2.2, with the string "258EAFA5- E914-47DA-95CA-C5AB0DC85B11", taking the SHA-1 hash of this concatenated value to obtain a 20-byte value and base64- encoding (see Section 4 of [RFC4648]) this 20-byte hash. The ABNF [RFC2616] of this header field is defined as follows: Sec-WebSocket-Accept = base64-value-non-empty base64-value-non-empty = (1*base64-data [ base64-padding ]) | base64-padding base64-data = 4base64-character base64-padding = (2base64-character "==") | (3base64-character "=") base64-character = ALPHA | DIGIT | "+" | "/"
(来自WebSocket协议规范)
我怀疑你试图连接的服务器不是一个特殊的WebSocket服务器,因此不响应客户端握手的HTTP响应。
您确定以正确的方式接受连接吗?
请看看如何以编程方式调用WebSocket(使用PHP)?,在交换数据的开始,有一些东西发送给客户端,也许这是正确的方向。
如果你的服务器一切正常,那么这个脚本应该工作得很好http://jsbin.com/qibevu/1/edit如果你把echo websocket服务器改为你自己的。
我个人推荐纯javascript new WebSocket('ws://');
,它很容易使用,只要有一个后端套接字监听相同的地址和端口,就会连接。