本篇文章给大家分享的是有关Window/Linux下的Socket Server代码,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。
Windows下
一、代码
#include <iostream> #include <WinSock2.h> using namespace std; #pragma comment(lib,"Ws2_32.lib") void main() { WORD wVersionRequested; WSADATA wsaData; int err; wVersionRequested = MAKEWORD(2, 2); err = WSAStartup(wVersionRequested, &wsaData); if (err != 0) { printf("WSAStartup failed with error: %d\n", err); return; } if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2) { printf("Could not find a usable version of Winsock.dll\n"); WSACleanup(); return; } else printf("The Winsock 2.2 dll was found okay\n"); // SOCKET sockSrv = socket(AF_INET, SOCK_STREAM, 0); SOCKADDR_IN addrSrv; addrSrv.sin_family = AF_INET; addrSrv.sin_port = htons(80); addrSrv.sin_addr.S_un.S_addr = htonl(ADDR_ANY); bind(sockSrv, (SOCKADDR*)&addrSrv, sizeof(addrSrv)); listen(sockSrv, 5); SOCKADDR_IN addrConn; int len = sizeof(addrConn); int n = 0; while(1) { // SOCKET sockConn = accept(sockSrv, (SOCKADDR*)&addrConn, &len); cout<<"ip:"<<inet_ntoa(addrConn.sin_addr)<<", port:"<<addrConn.sin_port<<endl; // char buf[1024] = {0}; recv(sockConn, buf, 1024, 0); cout<<"server recv:"<<endl<<buf<<endl<<endl; // char send_buf[100] = {0}; sprintf(send_buf, "%s%d", "yes.", n); n++; cout<<"000000000000n:"<<n<<", send_buf:"<<send_buf<<endl; int ret = send(sockConn, send_buf, strlen(send_buf), 0); cout<<"ret:"<<ret<<endl<<endl; //shutdown(sockConn, SD_BOTH); closesocket(sockConn); } closesocket(sockSrv); }
二、运行
2.1 运行
1. 运行上述代码。
2. 在浏览器中访问127.0.0.1
2.2 结果
Linux下
一、代码
#include <iostream> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <string.h> using namespace std; int main(int argc, char* argv[]) { int sock_srv = socket(AF_INET, SOCK_STREAM, 0); struct sockaddr_in addr_srv; bzero(&addr_srv, sizeof(struct sockaddr_in)); addr_srv.sin_addr.s_addr = htonl(INADDR_ANY); addr_srv.sin_family = AF_INET; addr_srv.sin_port = htons(81); bind(sock_srv, (struct sockaddr*)&addr_srv, sizeof(struct sockaddr)); listen(sock_srv, 5); struct sockaddr_in addr_conn; socklen_t len = sizeof(struct sockaddr_in); while(1) { int sock_conn = accept(sock_srv, (struct sockaddr*)&addr_conn, &len); cout<<"ip:"<<inet_ntoa(addr_conn.sin_addr)<<", port:"<<addr_conn.sin_port<<endl; char buf[1024] = {0}; read(sock_conn, buf, 1024); cout<<"server recv:"<<endl<<buf<<endl<<endl; write(sock_conn, "yes", strlen("yes")); shutdown(sock_conn, SHUT_RDWR); close(sock_conn); } close(sock_srv); return 0; }
二、运行
2.1 运行
1. 编译上述代码生成test,执行./test。
2. 在浏览器中访问202.85.220.123:81。
2.2 结果
以上就是Window/Linux下的Socket Server代码,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。