PHP Socket编程(2)

PHP Client

Step.1 设置变量主机“Host"和端口”Port"

$host = "127.0.0.1";
$port = 5353;
// No Timeout 
set_time_limit(0);


注意主机IP地址和端口号必须和Server端一致。

Step2. 创建Socket

$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");


Step3. 与Server连接

$result = socket_connect($socket, $host, $port) or die("Could not connect toserver\n");


注意需指定连接的主机地址和端口号。


Step4. 写入Server端socket

socket_write($socket, $message, strlen($message)) or die("Could not send data to server\n");
在这一步中,客户端socket将数据传到服务端socket.


Step 5: 接收服务器端返回数据

$result = socket_read ($socket, 1024) or die("Could not read server response\n");
echo "Reply From Server  :".$result;

Step6 : 关闭客户端Socket

socket_close($socket);


完整代码:

服务器端Server.php:

// set some variables
$host = "127.0.0.1";
$port = 25003;
// don't timeout!
set_time_limit(0);
// create socket
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");
// bind socket to port
$result = socket_bind($socket, $host, $port) or die("Could not bind to socket\n");
// start listening for connections
$result = socket_listen($socket, 3) or die("Could not set up socket listener\n");

// accept incoming connections
// spawn another socket to handle communication
$spawn = socket_accept($socket) or die("Could not accept incoming connection\n");
// read client input
$input = socket_read($spawn, 1024) or die("Could not read input\n");
// clean up input string
$input = trim($input);
echo "Client Message : ".$input;
// reverse client input and send back
$output = strrev($input) . "\n";
socket_write($spawn, $output, strlen ($output)) or die("Could not write output\n");
// close sockets
socket_close($spawn);
socket_close($socket);

客户端client.php

$host    = "127.0.0.1";
$port    = 25003;
$message = "Hello Server";
echo "Message To server :".$message;
// create socket
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");
// connect to server
$result = socket_connect($socket, $host, $port) or die("Could not connect to server\n");  
// send string to server
socket_write($socket, $message, strlen($message)) or die("Could not send data to server\n");
// get server response
$result = socket_read ($socket, 1024) or die("Could not read server response\n");
echo "Reply From Server  :".$result;
// close socket
socket_close($socket);



你可能感兴趣的:(PHP Socket编程(2))