2.1、tcp做事源码

<?php

/

phpsocket启动服务62php应用原生socket创立tcp办事 GraphQL

Copyright(C) Iamasb

@project : 3、workerman干系知识点

@explain : 原生socket创建创建tcp做事

@filename : socket_tcp.php

@author : Iamasb

/

// 创建tcp

if (!($resource = socket_create(AF_INET,SOCK_STREAM,SOL_TCP))) {

echo \公众socket create is error\公众;

exit();

}

// 绑定当前主机和端口

if (!socket_bind($resource,'0.0.0.0','1234')) {

echo \公众socket bind is error\"大众;

exit();

}

// 启动监听

if (!socket_listen($resource)) {

echo \"大众socket listen is error\公众;

exit();

}

// 设置端口复用

if (!socket_set_option($resource, SOL_SOCKET, SO_REUSEADDR, 1)) {

echo 'Unable to set option on socket: '. socket_strerror(socket_last_error()) . PHP_EOL;

exit;

}

while (1) {

$client = socket_accept($resource);

socket_getsockname($client,$addr,$port);

echo 'local-&gt;',$addr,'-->',$port,PHP_EOL;

socket_getpeername($client,$addr,$port);

echo 'remote->',$addr,'-->',$port,PHP_EOL;

$string = socket_read($client,1024);

echo $string;

socket_write($client,$string,strlen($string));

socket_close($client);

}

2.2、启动tcp做事

3、测试

测试有两种办法,一种是通过编写客户端,另一种是通过telnet

3.1、通过telnet

此时tcp做事真个显示结果

3.2、通过socket编写tcp客户端,并实行客户端

<?php

/

tcp 客户端

/

if (!($resource = socket_create(AF_INET,SOCK_STREAM,SOL_TCP))) {

echo \"大众socket create is error\公众;

exit();

}

if (!socket_connect($resource,'127.0.0.1','1234')) {

echo 'connect is error';

exit();

}

$string = 'hello world';

echo socket_send($resource,$string,strlen($string),MSG_EOF);

echo socket_read($resource,1024);