客户端上的套接字连接不起作用

时间:2019-05-08 14:04:09

标签: php sockets client

我正在尝试通过在本地计算机上创建客户端文件来连接到服务器端套接字。下面是我的php代码:

客户端文件php:

<?php
     set_time_limit(0);

     $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

     $res = socket_connect($socket, 'localhost', 11500) or die(socket_strerror(socket_last_error($socket)));

     $input = "<sending some input parameters to server side>";

     socket_write($socket, $input, strlen($input));
     $res = socket_read($socket, 1024);

     echo $res;

     socket_close($socket);
?>

服务器端文件:

<?php
     set_time_limit(0);

     $address = "<hostname>";
     $port = <port>;

     $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

     socket_listen($socket);

     $client = socket_accept($socket);

     $input = socket_read($client, 1024);

     //---- Performing some server side functions and returning output

     socket_write($client, $output);
     socket_close($socket);

 ?>

但是未显示任何输出并给出错误,“连接被拒绝”。

1 个答案:

答案 0 :(得分:1)

您需要在服务器端使用socket_bind,以便它与端口和给定的主机名绑定。尝试使用以下代码:

<?php
     set_time_limit(0);

     $address = "<hostname>";
     $port = <port>;

     $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

     socket_bind($socket, $address, $port) or die("Can't bind the socket");

     socket_listen($socket);

     $client = socket_accept($socket);

     $input = socket_read($client, 1024);

     //---- Performing some server side functions and returning output

     socket_write($client, $output);
     socket_close($socket);

 ?>