[英]php socket connections
我正在尝试使用以下代码创建一个php tcp / ip服务器:
<?php
// set some variables
$host = "localhost";
$port = 3804;
// 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, 3) or die("Could not set up socket listener\n");
// accept incoming connections
// spawn another socket to handle communication
$spawn = socket_accept($socket) or die("Could not accept incoming connection\n");
// read client input
$input = socket_read($spawn, 1024) or die("Could not read input\n");
// clean up input string
$input = trim($input);
// reverse client input and send back
$output = strrev($input) . "\n";
socket_write($spawn, $output, strlen ($output)) or die("Could not write output\n");
// close sockets
socket_close($spawn);
socket_close($socket);
?>
我随机选择在3804端口上工作,当我试图telnet到我的主机上的那个端口我无法建立连接..我需要在服务器上做更多的设置吗?托管的php脚本,为了让我的php脚本能听到那个端口?
由于您将"localhost"
作为socket_bind
的第二个参数socket_bind
,因此您的套接字只会侦听来自localhost
解析的地址的连接,通常为127.0.0.1。 设置$host = '0.0.0.0';
允许来自世界各地的连接。
您可能还需要配置防火墙以允许通过端口3804的连接。
该代码适用于我。 您是从apache还是其他Web服务器运行此代码? 你试过用php -a
运行这些行吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.