服务端
<?php
/**
* Created by PhpStorm.
* User: LeoKim
* Date: 2017/5/12
* Time: 23:05
*/
class Server{
private $serv;
private $test;
public function __construct()
{
$this->serv = new swoole_server("0.0.0.0", 9502);
$this->serv->set(
array(
'worker_num' => 1,
)
);
$this->serv->on('Start', array($this, 'onStart'));
$this->serv->on('Connect', array($this, 'onConnect'));
$this->serv->on('Receive', array($this, 'onReceive'));
$this->serv->on('Close', array($this, 'onClose'));
$this->serv->start();
}
public function onStart( $serv ) {
echo "Start\n";
}
public function onConnect( $serv, $fd, $from_id ) {
echo "Client {$fd} connect\n";
}
public function onClose( $serv, $fd, $from_id ) {
echo "Client {$fd} close connection\n";
}
public function onReceive( swoole_server $serv, $fd, $from_id, $data){
echo "Get Message From Client {$fd}:{$data}\n";
foreach($serv->connections as $client){
if($fd != $client)
$serv->send($client, $data);
}
}
}
$server = new Server();
客户端
<?php
/**
* Created by PhpStorm.
* User: LeoKim
* Date: 2017/5/12
* Time: 23:13
*/
$socket = stream_socket_client("tcp://127.0.0.1:9502", $errno, $errstr, 30);
function OnRead()
{
global $socket;
$buffer = stream_socket_recvfrom($socket, 1024);
if(!$buffer)
{
echo "Server clised\n";
}
echo "\nRECV: {$buffer}\n";
fwrite(STDOUT, "Enter Msg:");
}
function onWrite()
{
global $socket;
echo "on Write\n";
}
function onInput()
{
global $socket;
$msg = trim(fgets(STDIN));
if($msg == 'exit'){
swoole_event_exit();
exit();
}
swoole_event_write($socket, $msg);
fwrite(STDOUT, "Enter Msg:");
}
swoole_event_add($socket, 'onRead', 'onWrite');
swoole_event_add(STDIN, 'onInput');
fwrite(STDOUT, "Enter Msg:");


