服务端
<?php
error_reporting(E_ALL);
set_time_limit(0);
$ip = "127.0.0.1";
$port = 1935;
function show_msg($msg){
echo iconv("UTF-8", "gb2312//IGNORE", $msg);
}
$socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
if($socket < 0) {
show_msg("socket_create() 失败的原因是:" . socket_strerror($socket) . "
");
exit;
}
if (!socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1)) {
show_msg("socket_set_option() 失败的原因是:" . socket_strerror($socket) . "
");
exit;
}
if (!socket_set_nonblock($socket)) {
show_msg("socket_set_nonblock() 失败的原因是:" . socket_strerror($socket) . "
");
exit;
}
$ret = socket_bind($socket, $ip, $port);
if (!$ret) {
show_msg("socket_bind() 失败的原因是:" . socket_strerror($socket) . "
");
exit;
}
$ret = socket_listen($socket, 1);
if ($ret < 0 ) {
show_msg("socket_listen() 失败的原因是:" . socket_strerror($socket) . "
");
exit;
}
$clients = array($socket);
while(true) {
$reads = $clients;
$writes=null;
$execs=null;
if(socket_select($reads, $writes, $execs, 2) < 1){
continue;
}
if(in_array($socket,$reads)) {
$newsock = socket_accept($socket);
socket_getpeername($newsock,$remoteIP,$remotePort);
$userSN = $remoteIP.'_'.$remotePort;
show_msg("-------------有新的连接($userSN):,客户数:".count($clients)."-------------
");
$clients[$userSN] = $newsock;
}
foreach($reads as $read_sock) {
if($read_sock == $socket){
continue;
}
$data = @socket_read($read_sock, 2048, PHP_BINARY_READ);
socket_getpeername($read_sock, $remoteIP, $remotePort);
$userSN = $remoteIP.'_'.$remotePort;
if($data === false){
socket_close($read_sock);
unset($clients[$userSN]);
show_msg("($userSN)已断开连接
");
continue;
}
show_msg("从($userSN)接收消息:,$data
");
//广播
foreach($clients as $client){
if($client != $socket){
socket_getpeername($read_sock, $remoteIP, $remotePort);
$userSN = $remoteIP.'_'.$remotePort;
show_msg("发送消息到($userSN):$data
");
@socket_write($client,$data,strlen($data));
}
}
}
}
客户端
<?php
error_reporting(E_ALL);
set_time_limit(0);
$ip = "127.0.0.1";
$port = 1935;
function show_msg($msg){
echo iconv("UTF-8", "gb2312//IGNORE", $msg);
}
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket < 0) {
show_msg("socket_create() 失败的原因是:" . socket_strerror($socket) . "
");
exit;
}
$ret = socket_connect($socket, $ip, $port);
if ($ret < 0) {
show_msg("socket_connect() 失败的原因是:" . socket_strerror($ret) . "
");
exit;
}
while(true){
$msg = "sadfasdfasdfasdf====";
socket_write($socket, $msg, strlen($msg));
show_msg("发送消息:$msg
");
$msg = socket_read($socket, 8192);
if($msg){
show_msg("接收消息:$msg
");
}
sleep(1);
}
socket_close($socket);
echo show_msg("关闭OK
");
?>