phpsocket服务端和VC客户端通信实例
生活随笔
收集整理的這篇文章主要介紹了
phpsocket服务端和VC客户端通信实例
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
首先編輯php.ini, 打開extension=php_sockets.dll, 修改完成之后重啟apache
可以加下如下代碼判斷是否開啟php_sockets
if(extension_loaded('sockets')) {echo "已開啟"; } else {echo "未開啟"; }服務端代碼 server.php <?phpset_time_limit(0);$host="localhost";$port=8080;//創建一個連接$socket=socket_create(AF_INET,SOCK_STREAM,SOL_TCP)or die("cannot create socket\n");//綁定socket到端口$result=socket_bind($socket,$host,$port) or die("cannot bind port to socket\n");//開始監聽這個端口$result=socket_listen($socket,4) or die("could not set up socket listen\n");//接受連接,另一個socket來處理通信$msgsock=socket_accept($socket) or die("cannot accept incoming connection\n");if($msgsock){echo "connect";echo date("Y-m-d H:i:s D a");echo "\n";}//讀取客戶端發送過來的信息$input=socket_read($msgsock,1024) or die("cannot read input\n");$input=trim($input);echo "recv:$input\n";//發送數據到客戶端$output="output\n";socket_write($msgsock,$output,strlen($output)) or die("cannot write");//關閉socket連接socket_close($msgsock);socket_close($socket);?>
VC客戶端代碼 // phpsocket.cpp : 定義控制臺應用程序的入口點。 //#include "stdafx.h"#include <windows.h> #pragma comment(lib,"ws2_32.lib")int _tmain(int argc, _TCHAR* argv[]) {//初始化套接字版本WSAData wsaData;WSAStartup(MAKEWORD(2,2),&wsaData);//創建SocketSOCKET Socket_Server;Socket_Server = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);if (Socket_Server == INVALID_SOCKET){printf("Socket error");return 0;}//初始化地址sockaddr_in ClientAddr;ClientAddr.sin_family = AF_INET;ClientAddr.sin_port = htons(8080);ClientAddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");//循環連接while (true){//連接if (connect(Socket_Server,(LPSOCKADDR)&ClientAddr,sizeof(ClientAddr)) == SOCKET_ERROR){printf("connect error\n");Sleep(3000);continue;}printf("連接成功");break; }//發送if (send(Socket_Server,"online",sizeof("online"),0) == SOCKET_ERROR){printf("send error");return 0;}char revData[1024] = {0};int ret = recv(Socket_Server,revData,1024,0);if (ret > 0){MessageBoxA(0,revData,0,0);}//關閉Socketclosesocket(Socket_Server);WSACleanup();return 0; }
另外附上PHP客戶端代碼供參考
<?phpset_time_limit(0);$host="localhost";$port=8080;//創建一個socket$socket=socket_create(AF_INET,SOCK_STREAM,SOL_TCP)or die("cannot create socket\n");//連接$conn=socket_connect($socket,$host,$port) or die("cannot connect server\n");if($conn){echo "connect ok\n";}//發送數據socket_write($socket,"online") or die("cannot write data\n");//接收數據$buffer=socket_read($socket,1024,PHP_NORMAL_READ);if($buffer){echo "recv:".$buffer."\n";} socket_close($socket); ?>與50位技術專家面對面20年技術見證,附贈技術全景圖
總結
以上是生活随笔為你收集整理的phpsocket服务端和VC客户端通信实例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux内核通用提权漏洞expliot
- 下一篇: CentOS生成自签名证书配置Apach