您好我有一个用PHP编写的正在运行的套接字服务器。
服务器正在侦听连接..任何想法我的客户端(用javascript编写)将如何连接到服务器并向其发送数据?
PS:我只知道如何将php客户端连接到套接字服务器,但不确定如何连接javascript客户端。
谢谢大家的时间。
答案 0 :(得分:6)
回答一个旧问题,以防人们通过Google找到它。
如今几乎所有当代浏览器都支持WebSocket Javascript API。通过WS,浏览器中的客户端JS可以打开全双工套接字到用PHP或其他语言编写的服务器。服务器必须实现WS协议,但现在有用于PHP,Java和其他语言的WS库。
在撰写本文时,WS实现似乎仍然是一个移动目标,但是,我目前正在使用与WS / Java服务器通信的WS / JS浏览器客户端,它似乎确实在工作
以您选择的服务器语言为WS实现建议Google搜索。
希望这有帮助!
答案 1 :(得分:3)
我为客户端使用标准WebSocket API。 服务器端的核心PHP socket。
知道,发送和接收数据使用带有websocket的浏览器上的标题。但代码是PHP套接字,无标头发送和接收,只发送普通数据。
因此我们需要在socketing服务器端模拟标头。
为了学习并知道如何做,我写了这个清晰的示例代码,使用此代码,您可以向服务器发送一个短语,并在客户端接收反向短语。
server.php
<?php
//Code by: Nabi KAZ <www.nabi.ir>
// set some variables
$host = "127.0.0.1";
$port = 5353;
// don't timeout!
set_time_limit(0);
// create socket
$socket = socket_create(AF_INET, SOCK_STREAM, 0)or die("Could not create socket\n");
// bind socket to port
$result = socket_bind($socket, $host, $port)or die("Could not bind to socket\n");
// start listening for connections
$result = socket_listen($socket, 20)or die("Could not set up socket listener\n");
$flag_handshake = false;
$client = null;
do {
if (!$client) {
// accept incoming connections
// client another socket to handle communication
$client = socket_accept($socket)or die("Could not accept incoming connection\n");
}
$bytes = @socket_recv($client, $data, 2048, 0);
if ($flag_handshake == false) {
if ((int)$bytes == 0)
continue;
//print("Handshaking headers from client: ".$data."\n");
if (handshake($client, $data, $socket)) {
$flag_handshake = true;
}
}
elseif($flag_handshake == true) {
if ($data != "") {
$decoded_data = unmask($data);
print("< ".$decoded_data."\n");
$response = strrev($decoded_data);
socket_write($client, encode($response));
print("> ".$response."\n");
socket_close($client);
$client = null;
$flag_handshake = false;
}
}
} while (true);
// close sockets
socket_close($client);
socket_close($socket);
function handshake($client, $headers, $socket) {
if (preg_match("/Sec-WebSocket-Version: (.*)\r\n/", $headers, $match))
$version = $match[1];
else {
print("The client doesn't support WebSocket");
return false;
}
if ($version == 13) {
// Extract header variables
if (preg_match("/GET (.*) HTTP/", $headers, $match))
$root = $match[1];
if (preg_match("/Host: (.*)\r\n/", $headers, $match))
$host = $match[1];
if (preg_match("/Origin: (.*)\r\n/", $headers, $match))
$origin = $match[1];
if (preg_match("/Sec-WebSocket-Key: (.*)\r\n/", $headers, $match))
$key = $match[1];
$acceptKey = $key.'258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
$acceptKey = base64_encode(sha1($acceptKey, true));
$upgrade = "HTTP/1.1 101 Switching Protocols\r\n".
"Upgrade: websocket\r\n".
"Connection: Upgrade\r\n".
"Sec-WebSocket-Accept: $acceptKey".
"\r\n\r\n";
socket_write($client, $upgrade);
return true;
} else {
print("WebSocket version 13 required (the client supports version {$version})");
return false;
}
}
function unmask($payload) {
$length = ord($payload[1]) & 127;
if ($length == 126) {
$masks = substr($payload, 4, 4);
$data = substr($payload, 8);
}
elseif($length == 127) {
$masks = substr($payload, 10, 4);
$data = substr($payload, 14);
}
else {
$masks = substr($payload, 2, 4);
$data = substr($payload, 6);
}
$text = '';
for ($i = 0; $i < strlen($data); ++$i) {
$text .= $data[$i] ^ $masks[$i % 4];
}
return $text;
}
function encode($text) {
// 0x1 text frame (FIN + opcode)
$b1 = 0x80 | (0x1 & 0x0f);
$length = strlen($text);
if ($length <= 125)
$header = pack('CC', $b1, $length);
elseif($length > 125 && $length < 65536)$header = pack('CCS', $b1, 126, $length);
elseif($length >= 65536)
$header = pack('CCN', $b1, 127, $length);
return $header.$text;
}
client.htm
<html>
<script>
//Code by: Nabi KAZ <www.nabi.ir>
var socket = new WebSocket('ws://localhost:5353');
// Open the socket
socket.onopen = function(event) {
var msg = 'I am the client.';
console.log('> ' + msg);
// Send an initial message
socket.send(msg);
// Listen for messages
socket.onmessage = function(event) {
console.log('< ' + event.data);
};
// Listen for socket closes
socket.onclose = function(event) {
console.log('Client notified socket has closed', event);
};
// To close the socket....
//socket.close()
};
</script>
<body>
<p>Please check the console log of your browser.</p>
</body>
</html>
手动:首先在CLI上运行php server.php
,然后在浏览器上打开http://localhost/client.htm
。
你可以看到结果:
http://localhost/client.htm
> I am the client.
< .tneilc eht ma I
php server.php
< I am the client.
> .tneilc eht ma I
请注意,它只是测试发送和接收数据的示例代码,对执行工作没有用。
我建议你使用这些项目:
https://github.com/ghedipunk/PHP-Websockets
https://github.com/esromneb/phpwebsocket
https://github.com/acbrandao/PHP/tree/master/ws
https://github.com/srchea/PHP-Push-WebSocket/
http://socketo.me/
我还建议您阅读这些文章以获取更多详细信息:
http://www.abrandao.com/2013/06/websockets-html5-php/
http://cuelogic.com/blog/php-and-html5-websocket-server-and-client-communication/
http://srchea.com/build-a-real-time-application-using-html5-websockets
答案 2 :(得分:0)
我不知道为JS提供任意套接字功能的任何东西。对Web Sockets的支持有限(我认为这将要求您修改服务器以符合空间)。如果做不到这一点,简单的XHR可能会满足您的需求(这需要您修改服务器以充当Web服务)。如果服务在与页面不同的原点上运行,则您需要使用CORS或使用JSONP之类的解决方法。
答案 3 :(得分:0)
答案 4 :(得分:-2)
简短地说 - 你不能这样做 - 让客户端代码打开套接字连接是一个安全漏洞。
但是,您可以模拟 - 将您的数据作为AJAX请求发送到另一个PHP页面,然后使该PHP页面通过套接字进行通信。
2017年更新:
与此同时,websockets成了一件事。请注意,websocket协议与generic networking sockets
不同