首先要setup 好server side , 變更host and port
完成後要係putty 開啟server
php -q socket_server.php
<?php //php -q socket_server.php // 设置一些基本的变量 global $lat,$lnt; $host = "192.168.0.1"; $port = 8888; // 设置超时时间 set_time_limit(0); // 创建一个Socket $commonProtocol = getprotobyname("tcp"); $socket = socket_create(AF_INET, SOCK_STREAM, $commonProtocol); //绑定Socket到端口 $result = socket_bind($socket, $host, $port) or die("Could not bind to socket\n"); $ret = socket_listen($socket, 5); if($ret){ while (true){ $spawn = socket_accept($socket) or die("Could not accept incoming connection\n");; echo("socket connected\n"); if(!$spawn) break; $output = "Welcome to the PHP Test Server.....nice\n"; socket_write($spawn, $output, strlen ($output)) or die("error\n"); while($input = socket_read($spawn, 64)){ echo($input); } echo("\n"); socket_close($spawn); } } ?>
Client Side
<?php // 设置一些基本的变量 $host = "192.168.0.1"; $port = 8888; // 设置超时时间 set_time_limit(0); // 创建一个Socket $commonProtocol = getprotobyname("tcp"); $socket = socket_create(AF_INET, SOCK_STREAM, $commonProtocol); if(!$socket) echo "can't create socket"; //绑定Socket到端口 $result = socket_connect($socket, $host, $port) or die(socket_strerror()); if($result){ $output="hello server!,connie";//lat:30.582029016593196;lnt:103.98662567138672 socket_write($socket, $output, strlen ($output)); $input = socket_read($socket, 1024); echo($input); } ?>
之後係web browser 開client url , 便可以
Comment feed