php中的websocket不会连接到server.php

时间:2014-09-30 18:21:25

标签: php sockets websocket

这是我的代码,这项工作完美地发送了消息。但server.php没有收到它。现在,如果我使用javascript和html5并发送到ws:// localhost:8000 / instantchat / server.php它当然有效。我猜我需要以某种方式在socket_connect函数上指定server.php文件。如果我使用ws URL更改localhost或仅使用直接路径更改localhost将无法查找主机,因此它将无法连接。任何想法如何做到这一点?我确实去了php dot net并在google上随处可见。任何帮助,将不胜感激

<?php

if(!($sock = socket_create(AF_INET, SOCK_STREAM, 0)))
{
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);

    die("Couldn't create socket: [$errorcode] $errormsg \n");
}
echo "Socket created \n";

//Connect socket to remote server
if(!socket_connect($sock , 'localhost' , 8000))
{
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);

    die("Could not connect: [$errorcode] $errormsg \n");
}

echo "Connection established \n";

 $message = array( 'action' => 'chat_text' , 'user_id' => '4' , 'chat_text' => '');
 $message = json_encode($message);

//Send the message to the server
if( !socket_send ( $sock , $message , '55' , 0))
{
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);

    die("Could not send data: [$errorcode] $errormsg \n");
} else echo "Message send successfully \n";

1 个答案:

答案 0 :(得分:0)

您在此处编写的代码未正确协商WebSocket连接。你需要*使用WebSocket库来做到这一点;请参阅"Is native PHP support for Web Sockets available?"以获取PHP WebSocket库列表。

*:虽然技术上可以根据the specification自己编写客户端,但它相当复杂,除非你有一些非常不寻常的要求,否则不宜自己这样做。