服務端php
<?php
error_reporting(E_ALL);
set_time_limit(0);socket
$ip = "127.0.0.1";
$port = 1935;ip
function show_msg($msg){
echo iconv("UTF-8", "gb2312//IGNORE", $msg);
}rem
$socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
if($socket < 0) {
show_msg("socket_create() 失敗的緣由是:" . socket_strerror($socket) . "\n");
exit;
}get
if (!socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1)) {
show_msg("socket_set_option() 失敗的緣由是:" . socket_strerror($socket) . "\n");
exit;
}it
if (!socket_set_nonblock($socket)) {
show_msg("socket_set_nonblock() 失敗的緣由是:" . socket_strerror($socket) . "\n");
exit;
}io
$ret = socket_bind($socket, $ip, $port);
if (!$ret) {
show_msg("socket_bind() 失敗的緣由是:" . socket_strerror($socket) . "\n");
exit;
}function
$ret = socket_listen($socket, 1);
if ($ret < 0 ) {
show_msg("socket_listen() 失敗的緣由是:" . socket_strerror($socket) . "\n");
exit;
}cli
$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)."-------------\n");
$clients[$userSN] = $newsock;
}foreach
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)已斷開鏈接\n");
continue;
}
show_msg("從($userSN)接收消息:,$data\n");
//廣播
foreach($clients as $client){
if($client != $socket){
socket_getpeername($read_sock, $remoteIP, $remotePort);
$userSN = $remoteIP.'_'.$remotePort;
show_msg("發送消息到($userSN):$data\n");
@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) . "\n");
exit;
}
$ret = socket_connect($socket, $ip, $port);
if ($ret < 0) {
show_msg("socket_connect() 失敗的緣由是:" . socket_strerror($ret) . "\n");
exit;
}
while(true){
$msg = "sadfasdfasdfasdf====";
socket_write($socket, $msg, strlen($msg));
show_msg("發送消息:$msg\n");
$msg = socket_read($socket, 8192);
if($msg){
show_msg("接收消息:$msg\n");
}
sleep(1);
}
socket_close($socket);
echo show_msg("關閉OK\n");
?>