今天就跟大家聊聊有关使用PHP怎么实现TCP服务端和客户端功能,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。
1,修改,打开扩展=php_sockets.dll
2,服务端程序SocketServer。php
& lt; php ?//确保在连接客户端时不会超时 set_time_limit (0);//设置IP和端口号 时间=美元address “127.0.0.1"; 时间=美元port 3046;/* * ,*创建一个插座 ,* AF_INET=是ipv4 如果用ipv6,则参数为,AF_INET6 ,* SOCK_STREAM为套接字的tcp类型,如果是UDP则使用SOCK_DGRAM */$ sock =, socket_create (AF_INET, SOCK_STREAM,, SOL_TCP),或是死亡(“socket_create(),失败:“,只socket_strerror (socket_last_error()),只“/n");//阻塞模式 socket_set_block(袜子),或是死亡(“socket_set_block(),失败:“,只socket_strerror (socket_last_error()),只“/n");//绑定到套接字端口 result 美元;=,socket_bind(袜子美元,,地址,端口)美元,或是死亡(“socket_bind(),失败:“,只socket_strerror (socket_last_error()),只“/n");//开始监听 $ result =, socket_listen(袜子美元,,4),或是死亡(“socket_listen(),失败:“,只socket_strerror (socket_last_error()),只“/n"); echo “好\ nBinding 从而socket 提醒地址:美元port 美元;……,“; echo “好\ nNow ready 用accept 连接。\ nListening 提醒,socket ……, \ n"; do {,//never stop 从而守护进程//它才能接收连接请求并调用一个子连接插座来处理客户端和服务器间的信息 msgsock 美元;才能=,socket_accept(袜子),或是死亡(“socket_accept(),:失败,原因:,“,只socket_strerror (socket_last_error()),只“/n"); 而才能(1){ ,,,//读取客户端数据 ,,,echo “Read client data \ n"; ,,,//socket_read函数会一直读取客户端数据,直到遇见\ n \ t或者\ 0字符。php脚本把这写字符看做是输入的结束符。 ,,,buf 美元;=,socket_read (msgsock美元,,8192); ,,,echo “Received 味精:,buf 美元;,\ n"; ,,,如果(buf 美元;==,“bye") { ,,,,,//接收到结束消息,关闭连接,等待下一个连接 ,,,,,socket_close ($ msgsock); ,,,,,继续; ,,,} ,,,//数据传送,向客户端写入返回结果 ,,,msg 美元;=,“welcome \ n"; ,,,socket_write (msgsock美元,,味精,strlen (msg)美元),或是死亡(“socket_write(),:失败,原因:,“,只socket_strerror (socket_last_error()),干净/n"); ,,} },while (真正的); socket_close(袜子); 祝辞;
3,客户端程序SocketClient。php
& lt; php ? set_time_limit (0); 时间=美元host “127.0.0.1"; 时间=美元port 3046; $ socket =, socket_create (AF_INET, SOCK_STREAM,, SOL_TCP)或死亡(“Could  not create 插座\ n"); connection 美元;=,socket_connect(插座美元,,主机,美元端口),或是死亡(“Could  not connet 服务器\ n"); socket_write(插座,美元,“hello socket"),或是死亡(“Write 失败\ n"); while (buff 美元;=,socket_read(插座,美元,1024年,PHP_NORMAL_READ)), { 回声才能(“Response 是:“,只buff 美元;只“\ n"); 回声才能(“input  what 你want 用say 用,服务器:\ n"); 时间=美元才能text fgets (STDIN); socket_write才能(插座,美元,美元文本); } socket_close(插座); 祝辞;
4,测试
运行服务端程序:C: \ wamp \ bin \ php \ php5.4.16 \ php。exe C: \ wamp \ www \ SocketServer。php
运行客户端程序:C: \ wamp \ bin \ php \ php5.4.16 \ php。exe C: \ wamp \ www \ SocketClient。php
如果遇到
致命错误:未定义的函数的调用socket_create ()。
1。找到php。ini,看<代码>扩展=php_gd2.dll> 代码,,和,<代码>=php_sockets延伸。dll 代码>扩展是否打开;
2。看<代码> phpInfo() 代码>显示的内容里,凹模块是否为启用;
我检查了一下,发现都是符合的。但错误仍然出现?怎么回事呢?
后来我才发现,原来是我在<代码> phpInfo() 代码>里看到的和在cmd窗口里使用的php不是同一个东西。
原因是我多次安装过php。先前的php在系统的环境变量里面注册了道路。所以在cmd窗口里使用的是以前的php。而在<代码> phpInfo() 代码>里显示的是现在的php的设置。
解决的办法很简单了,就把系统环境变量里的路径里,指向老的php的路径改为指向正在使用的php的路径。这样在cmd里的php和在浏览器里的php就是同一个东西了。