php socket 编程 tcp

server 端

  1. socket_create():创建一个套接字
  2. socket_bind():给套接字绑定名字
  3. socket_listen():监听套接字上的连接
  4. socket_set_nonblock():非阻塞
  5. socket_read():获得客户端输入内容
  6. socket_write():写数据到socket
<?php
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die('create fail');
socket_bind($sock, $ip, $port) or die('bind fail');
socket_listen($sock, 128) or die('listen fail');

socket_set_nonblock($sock);
while(true){
	$accept = socket_accept($sock);
	if(!$accept){
		echo 'accept fail' . PHP_EOL;
	} else {
		socket_write($accept, 'success', strlen('success'));
	}
}

socket_close($sock);


client 端

  1. socket_create()
  2. socket_connect()
  3. socket_write()
  4. socket_read()
<?php
$ip = '127.0.0.1';
$port = 9951;

$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die('create fail');

$connect = socket_connect($sock, $ip, $port) or die('connect fail');

//向服务端发送内容
socket_write($sock, 'test msg', strlen('test msg'));

//读取服务端返回内容
$server_msg = socket_read($sock, 1024);

echo 'server:' . $server_msg . PHP_EOL;

socket_close($sock); //关闭连接资源

黄铭博客
请先登录后发表评论
  • latest comments
  • 总共0条评论