适用于socket.io版本3的最新解决方案
https://github.com/socketio/socket.io-protocol#sample-session
下面是一个可用的服务器示例:
直接运行服务器:/usr/local/bin/node /socket_io/server/index.js
或通过“forever”运行服务器。
/usr/local/bin/forever -a -l /logs/socket.io/forever-log.log -o /logs/socket.io/forever-out.log -e /media/flashmax/var/logs/socket.io/forever-err.log start /socket_io/server/index.js
index.js文件内容(接收请求):
var io = require('/usr/local/lib/node_modules/socket.io')(8000);
io.sockets.on('connection', function (socket) {
socket.on('router', function (channel,newmessage) {
socket.broadcast.to(channel).emit('new_chat',newmessage);
});
socket.on('watch_for_me', function (chanelll) {
socket.join(chanelll);
});
socket.on('dont_watch', function (del_chanelll) {
socket.leave(del_chanelll);
});
});
PHP发送脚本
<?php
$site_name='http://127.0.0.1:8000/socket.io/?EIO=4&transport=polling&t=mytest';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $site_name);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
$output=substr($output, 1);
$decod=json_decode($output);
$site_name2=$site_name.'&sid='.$decod->sid;
curl_setopt($ch, CURLOPT_URL, $site_name2);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, '40');
$output = curl_exec($ch);
if ($output==='ok') {
curl_setopt($ch, CURLOPT_URL, $site_name2);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
}
if ($output==='ok') {
curl_setopt($ch, CURLOPT_URL, $site_name2);
curl_setopt($ch, CURLOPT_POST, true);
$message_send='{\\"uuuuu\\": \\"000\\",\\"ryyyd\\":\\"999\\",\\"hyyya\\":\\"<div class=\'fro9\'>llll</div><div class=\'9ig\'>iiiii</div><div class=\'ti9g\'>iiiii</div>\\"}';
curl_setopt($ch, CURLOPT_POSTFIELDS, "42[\"router\",\"chanel@id\",\"$message_send\"]");
$output = curl_exec($ch);
print_r($output);
}
$message_send='send 2 message';
curl_setopt($ch, CURLOPT_POSTFIELDS, "42[\"router\",\"chanel@id\",\"$message_send\"]");
$output = curl_exec($ch);
$message_send='send 3 message';
curl_setopt($ch, CURLOPT_POSTFIELDS, "42[\"router\",\"chanel@id\",\"$message_send\"]");
$output = curl_exec($ch);
curl_close($ch);
?>
额外奖励:针对Apache的设置 -> mod_proxy用于访问socket.io,可用于虚拟主机或整个服务器。
RewriteEngine on
RewriteCond %{QUERY_STRING} transport=polling [NC]
RewriteRule /(.*)$ http://127.0.0.1:8000/$1 [P,L]
ProxyRequests off
ProxyPass /socket.io/ ws://127.0.0.1:8000/socket.io/
ProxyPassReverse /socket.io/ ws://127.0.0.1:8000/socket.io/
s.RemoteAddress
部分。否则,请使用console.log
连接以查看来自哪个地址。每当发送数据到服务器时,s.on('data')
都应该触发。 - user1274820127.0.0.1
更改为localhost
可能会解决这个问题 - 希望尝试一下。同时,我也做了你所做的事情 - 检查它是否像有效的JSON一样,但显然这是一种不好的方法。 - user1274820