AutoCAD 3DMAX C语言 Pro/E UG JAVA编程 PHP编程 Maya动画 Matlab应用 Android
Photoshop Word Excel flash VB编程 VC编程 Coreldraw SolidWorks A Designer Unity3D
 首页 > PHP编程

PHP sockets程序实例代码

51自学网 2016-09-17 http://www.wanshiok.com
一个socket就像一个插头,它提供了两个进程间通信的方式。一般来说,它允许你在任意未被使用的端口进行接收或发送信息。那么怎样使用sockets呢?
socket 服务端的编写:

为了使问题不至于太复杂,这里我们写一个简单的例子,步骤如下:
·在指定的IP和端口创建一个socket 使用socket_create()和socket_bind()
·socket监听 使用socket_listen()
·等待来自客户端的链接 使用socket_accept()
·从socket读取数据 使用socket_read()
·输出数据后,关闭socket 使用socket_close()

下面是socketserver.php代码:
<?php//Set up some variables$maxBytes = 5000;$address = '127.0.0.1';$port = 33333;//Create the socket on the specified port.//$socket = socket_create_listen($port);$socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);socket_bind($socket,$address,$port);echo "server is listenning...";socket_listen($socket);//socket_set_nonblock($socket);//Wait for incoming connections.$connection = socket_accept($socket);print "Connection accepted/n";//When a connection has been accepted, read up to $maxBytes//then print the received message.$bytes = socket_read($connection, $maxBytes);echo "Message From Client: $bytes /n";//Close the socketsocket_close($socket);?>

 socket客户端的编写:

·在指定的端口创建一个socket 使用socket_create()
·使用刚刚创建的socket连接服务端的socket 使用socket_connect()
·给服务端发送消息 使用socket_send()
·关闭socket 使用socket_close()

socketclient.php代码如下:
<?php//Create a socket and connect it to the server.$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);socket_connect($socket, '127.0.0.1', 33333);//Create a message, and send it to the server on $socket.$message = "This is a message from the client./n";socket_send($socket, $message, strlen($message), MSG_OOB);//Close the socket.socket_close($socket);?>

在命令行下测试socket程序。如果你还没有在命令行下运行过php程序,请参考windows命令行下运行PHP程序。
以下是本人测试的过程和结果:
·运行socketserver.php

C:/Users/henrypoter>N:/wamp/bin/php/php5.3.8/php.exe  -f "N:/wamp/www/word/socketserver.php"
server is listenning...

运行socketclient.php
C:/Users/henrypoter>N:/wamp/bin/php/php5.3.8/php.exe  -f "N:/wamp/www/word/socketclient.php

·socketserver端的输出结果:
C:/Users/henrypoter>N:/wamp/bin/php/php5.3.8/php.exe  -f "N:/wamp/www/word/socketserver.php"
server is listenning...Connection accepted
Message From Client: This is a message from the client.

在php5.3.8版本下面测试socket_send()函数的第4个参数不能设置为MSG_EOF,MSG_EOR
可能是该版本的一个bug。参考:Missing MSG_EOR and MSG_EOF constants to sockets extension


说明
:本教程来源互联网或网友上传或出版商,仅为学习研究或媒体推广,wanshiok.com不保证资料的完整性。
 
上一篇:php无刷新上传文件代码  下一篇:php json_encode 中文 utf-8 乱码