2014-09-30 41 views
0

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

<?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"; 

回答

0

你在这里写的代码是不正确谈判一个WebSocket连接。你将需要*使用WebSocket库来做到这一点;有关PHP WebSocket库的列表,请参阅"Is native PHP support for Web Sockets available?"

*:虽然在技术上可以自己编写基于the specification客户端,这是相当复杂的,使得它不宜这样做你自己,除非你有一些非常异常要求。

+0

感谢暮色。现在试图解决这个问题,我已经把头撞到了墙上几个小时,尽管它现在连接并发送到文件。 (想通了),但收到的消息无法使用,它的每一步都会返回一个错误 – nodejsj 2014-09-30 19:01:54