在php中连接到套接字并发送消息的等价物是什么

时间:2014-09-18 22:29:30

标签: php sockets

在php中连接到套接字并发送消息的等价物

var msg = "hello Motto";
var wsUri = "ws://mylocalserver:9001/ab/server.php";    
    websocket = new WebSocket(wsUri); 
    websocket.send(msg);

这在javascript中很有用,我有一个显示消息的监听器文件。我想用php做同样的事情我很困惑我在网上找了很多文档但没有任何看似简单的任何帮助请

这里是我放在一起的PHP代码,但由于某些原因它不能正常工作我不会在另一端收到ping:

$sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);

$msg = "Ping !";
$len = strlen($msg);

socket_sendto($sock, $msg, $len, 0, 'ws://mylocalserver:9001/ab/server.php', 9001);
socket_close($sock);

这是失败的部分: 这有效:

socket_sendto($sock, $msg, $len, 0, 'mylocalserver', 9001);

但这不起作用:   socket_sendto($ sock,$ msg,$ len,0,'mylocalserver / ab / server.php',9001); 问题是我使用server.php来处理发送的消息。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

php websocket服务器示例

这些只是赤裸裸的骨头

//Create TCP/IP sream socket and return the socket resource
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

// Bind the source address
socket_bind($socket, 'localhost');

// Listen to incoming connection
socket_listen($socket);

// Accept new connections
socket_accept($socket);

// Handshake
$secKey = $headers['Sec-WebSocket-Key'];
$secAccept = base64_encode(pack('H*', sha1($secKey . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')));
$upgrade  = "HTTP/1.1 101 Web Socket Protocol Handshake\r\n" .
"Upgrade: websocket\r\n" .
"Connection: Upgrade\r\n" .
"WebSocket-Origin: $host\r\n" .
"WebSocket-Location: ws://$host:$port/deamon.php\r\n".
"Sec-WebSocket-Accept:$secAccept\r\n\r\n";
socket_write($client_conn,$upgrade,strlen($upgrade));

<小时/> 最好使用库在PHP中执行此操作,如下所示:https://github.com/ghedipunk/PHP-Websockets

如果需要学习太多,you can have a look at this tutorial会向您展示如何使用websockets建立实时聊天。 (这也用于php的websocket库)