原文作者:aircraft
原文地址:https://www.cnblogs.com/DOMLX/p/9601511.html
c++ 网络编程(一)TCP/UDP 入门级客户端与服务端交互代码
windows下:
TCP:
一.服务端代码
#define _WINSOCK_DEPRECATED_NO_WARNINGS#include <WinSock2.h>#include <stdio.h>#include <stdlib.h>#pragma comment(lib, "ws2_32.lib")void main() { WSADATA wsaData; int port = 5099; char buf[] = "Server: hello, I am a server....."; if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) { printf("Failed to load Winsock"); return; } //创建用于监听的套接字 SOCKET sockSrv = socket(AF_INET, SOCK_STREAM, 0); SOCKADDR_IN addrSrv; addrSrv.sin_family = AF_INET; addrSrv.sin_port = htons(port); //1024以上的端口号 addrSrv.sin_addr.S_un.S_addr = htonl(INADDR_ANY); int retVal = bind(sockSrv, (LPSOCKADDR)&addrSrv, sizeof(SOCKADDR_IN)); if (retVal == SOCKET_ERROR){ printf("Failed bind:%d\n", WSAGetLastError()); return; } if (listen(sockSrv, 10) == SOCKET_ERROR){ printf("Listen failed:%d", WSAGetLastError()); return; } SOCKADDR_IN addrClient; int len = sizeof(SOCKADDR);//等待客户请求到来 SOCKET sockConn = accept(sockSrv, (SOCKADDR *)&addrClient, &len); if (sockConn == SOCKET_ERROR){ printf("Accept failed:%d", WSAGetLastError()); //break; } printf("Accept client IP:[%s]\n", inet_ntoa(addrClient.sin_addr)); //发送数据 int iSend = send(sockConn, buf, sizeof(buf), 0); if (iSend == SOCKET_ERROR){ printf("send failed"); // break; } char recvBuf[100]; memset(recvBuf, 0, sizeof(recvBuf)); // //接收数据 recv(sockConn, recvBuf, sizeof(recvBuf), 0); printf("%s\n", recvBuf); closesocket(sockConn); closesocket(sockSrv); WSACleanup(); system("pause"); }
二.客户端代码
#define _WINSOCK_DEPRECATED_NO_WARNINGS#include <WinSock2.h>#include <stdio.h>#pragma comment(lib, "ws2_32.lib")void main() { //加载套接字 WSADATA wsaData; char buff[1024]; memset(buff, 0, sizeof(buff)); if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) { printf("Failed to load Winsock"); return; } SOCKADDR_IN addrSrv; addrSrv.sin_family = AF_INET; addrSrv.sin_port = htons(5099); addrSrv.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); //创建套接字 SOCKET sockClient = socket(AF_INET, SOCK_STREAM, 0); if (SOCKET_ERROR == sockClient){ printf("Socket() error:%d", WSAGetLastError()); return; } //向服务器发出连接请求 if (connect(sockClient, (struct sockaddr*)&addrSrv, sizeof(addrSrv)) == INVALID_SOCKET){ printf("Connect failed:%d", WSAGetLastError()); return; } else { //接收数据 recv(sockClient, buff, sizeof(buff), 0); printf("%s\n", buff); } //发送数据 char *buffSend = "hello, this is a Client...."; send(sockClient, buffSend, strlen(buffSend) + 1, 0); printf("%d", strlen(buffSend) + 1); //关闭套接字 closesocket(sockClient); WSACleanup(); system("pause"); }
怕某些小白不懂我详细说说运行,运行时先开服务端,在开客户端运行 ,也就是开两个cPP文件分别运行,两个cpp各是一个小项目代码 不要放在一起
这里的127.0.0.1是代表本地的地址,你们想实现两机交互就用对方的地址。
代码很简单,想要直接拿去,接下来直接看运行结果:
UDP:
windows下UDP服务端代码
#include<winsock2.h> #include<stdio.h> #include<string.h> #include<iostream> using namespace std; #pragma comment(lib,"ws2_32.lib") #define BUFFER_SIZE 1024 int main() { WSADATA WSAData; char receBuf[BUFFER_SIZE]; char Response[] = "" ; if (WSAStartup(MAKEWORD(2, 2), &WSAData) != 0) { printf ( "初始化失败" ); exit (1); } SOCKET sockServer = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if (sockServer == INVALID_SOCKET) { printf ( "Failed socket() \n" ); return 0; } SOCKADDR_IN addr_Server; //服务器的地址等信息 addr_Server.sin_family = AF_INET; addr_Server.sin_port = htons(4567); addr_Server.sin_addr.S_un.S_addr = INADDR_ANY; if (bind(sockServer, (SOCKADDR*)&addr_Server, sizeof (addr_Server)) == SOCKET_ERROR) { //服务器与本地地址绑定 printf ( "Failed socket() %d \n" , WSAGetLastError()); return 0; } SOCKADDR_IN addr_Clt; int fromlen = sizeof (SOCKADDR); while ( true ) { int last = recvfrom(sockServer, receBuf, 1024, 0, (SOCKADDR*)&addr_Clt, &fromlen); if (last>0) { //判断接收到的数据是否为空 receBuf[last] = '\0' ; //给字符数组加一个'\0',表示结束了。不然输出有乱码 if ( strcmp (receBuf, "bye" ) == 0) { cout << " 客户端不跟我聊天了..." << endl; closesocket(sockServer); return 0; } else { printf ( "接收到数据(%s):%s\n" , inet_ntoa(addr_Clt.sin_addr), receBuf); } } cout << "回复客户端消息:" ; cin >> Response; //给客户端回复消息 sendto(sockServer, Response, strlen (Response), 0, (SOCKADDR*)&addr_Clt, sizeof (SOCKADDR)); } closesocket(sockServer); WSACleanup(); return 0; } |
windows下UDP客户端端代码
#include<winsock2.h>#include<stdio.h>#include<string.h>#include<iostream>using namespace std;#pragma comment(lib,"ws2_32.lib")# define BUFFER_SIZE 1024 //缓冲区大小int main() { SOCKET sock_Client; //客户端用于通信的Socket WSADATA WSAData; char receBuf[BUFFER_SIZE]; //发送数据的缓冲区 char sendBuf[BUFFER_SIZE]; //接受数据的缓冲区 if (WSAStartup(MAKEWORD(2, 2), &WSAData) != 0) { printf("初始化失败!"); return -1; } //初始化 sock_Client = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);//创建客户端用于通信的Socket SOCKADDR_IN addr_server; //服务器的地址数据结构 addr_server.sin_family = AF_INET; addr_server.sin_port = htons(4567);//端口号为4567 addr_server.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); //127.0.0.1为本电脑IP地址 SOCKADDR_IN sock; int len = sizeof(sock); while (true) { cout << "请输入要传送的数据:"; cin >> sendBuf; sendto(sock_Client, sendBuf, strlen(sendBuf), 0, (SOCKADDR*)&addr_server, sizeof(SOCKADDR)); //int last=recv(sock_Client, receBuf, strlen(receBuf), 0); // (调用recv和recvfrom都可以) int last = recvfrom(sock_Client, receBuf, strlen(receBuf), 0, (SOCKADDR*)&sock, &len); if (last>0) { receBuf[last] = '\0'; //给字符数组加一个'\0',表示结束了。不然输出有乱码 if (strcmp(receBuf, "bye") == 0) { cout << "服务器不跟我聊天了..." << endl;//当服务器发来bye时,关闭socket closesocket(sock_Client); break; } else { printf("接收到数据:%s\n", receBuf); } } } closesocket(sock_Client); WSACleanup(); return 0; }
注:以下代码需在LINUX下运行 gcc什么的都可以
LINUX下:
一.TCP
linux下TCP服务端代码:
#include <stdio.h>#include <sys/types.h>#include <sys/socket.h>#include <netinet/in.h>#include <arpa/inet.h> int main(int argc, char *argv[]) { int server_sockfd;//服务器端套接字 int client_sockfd;//客户端套接字 int len; struct sockaddr_in my_addr; //服务器网络地址结构体 struct sockaddr_in remote_addr; //客户端网络地址结构体 int sin_size; char buf[BUFSIZ]; //数据传送的缓冲区 memset(&my_addr,0,sizeof(my_addr)); //数据初始化--清零 my_addr.sin_family=AF_INET; //设置为IP通信 my_addr.sin_addr.s_addr=INADDR_ANY;//服务器IP地址--允许连接到所有本地地址上 my_addr.sin_port=htons(8000); //服务器端口号 /*创建服务器端套接字--IPv4协议,面向连接通信,TCP协议*/ if((server_sockfd=socket(PF_INET,SOCK_STREAM,0))<0) { perror("socket error"); return 1; } /*将套接字绑定到服务器的网络地址上*/ if(bind(server_sockfd,(struct sockaddr *)&my_addr,sizeof(struct sockaddr))<0) { perror("bind error"); return 1; } /*监听连接请求--监听队列长度为5*/ if(listen(server_sockfd,5)<0) { perror("listen error"); return 1; }; sin_size=sizeof(struct sockaddr_in); /*等待客户端连接请求到达*/ if((client_sockfd=accept(server_sockfd,(struct sockaddr *)&remote_addr,&sin_size))<0) { perror("accept error"); return 1; } printf("accept client %s/n",inet_ntoa(remote_addr.sin_addr)); len=send(client_sockfd,"Welcome to my server/n",21,0);//发送欢迎信息 /*接收客户端的数据并将其发送给客户端--recv返回接收到的字节数,send返回发送的字节数*/ while((len=recv(client_sockfd,buf,BUFSIZ,0))>0)) { buf[len]='/0'; printf("%s/n",buf); if(send(client_sockfd,buf,len,0)<0) { perror("write error"); return 1; } } /*关闭套接字*/ close(client_sockfd); close(server_sockfd); return 0; }
linux下TCP客户端代码:
#include <stdio.h>#include <sys/types.h>#include <sys/socket.h>#include <netinet/in.h>#include <arpa/inet.h> int main(int argc, char *argv[]) { int client_sockfd; int len; struct sockaddr_in remote_addr; //服务器端网络地址结构体 char buf[BUFSIZ]; //数据传送的缓冲区 memset(&remote_addr,0,sizeof(remote_addr)); //数据初始化--清零 remote_addr.sin_family=AF_INET; //设置为IP通信 remote_addr.sin_addr.s_addr=inet_addr("127.0.0.1");//服务器IP地址 remote_addr.sin_port=htons(8000); //服务器端口号 /*创建客户端套接字--IPv4协议,面向连接通信,TCP协议*/ if((client_sockfd=socket(PF_INET,SOCK_STREAM,0))<0) { perror("socket error"); return 1; } /*将套接字绑定到服务器的网络地址上*/ if(connect(client_sockfd,(struct sockaddr *)&remote_addr,sizeof(struct sockaddr))<0) { perror("connect error"); return 1; } printf("connected to server/n"); len=recv(client_sockfd,buf,BUFSIZ,0);//接收服务器端信息 buf[len]='/0'; printf("%s",buf); //打印服务器端信息 /*循环的发送接收信息并打印接收信息(可以按需发送)--recv返回接收到的字节数,send返回发送的字节数*/ while(1) { printf("Enter string to send:"); scanf("%s",buf); if(!strcmp(buf,"quit") break; len=send(client_sockfd,buf,strlen(buf),0); len=recv(client_sockfd,buf,BUFSIZ,0); buf[len]='/0'; printf("received:%s/n",buf); } /*关闭套接字*/ close(client_sockfd); return 0; }
二.UDP
linux下UDP服务端代码
#include <stdio.h>#include <sys/types.h>#include <sys/socket.h>#include <netinet/in.h>#include <arpa/inet.h> int main(int argc, char *argv[]) { int server_sockfd; int len; struct sockaddr_in my_addr; //服务器网络地址结构体 struct sockaddr_in remote_addr; //客户端网络地址结构体 int sin_size; char buf[BUFSIZ]; //数据传送的缓冲区 memset(&my_addr,0,sizeof(my_addr)); //数据初始化--清零 my_addr.sin_family=AF_INET; //设置为IP通信 my_addr.sin_addr.s_addr=INADDR_ANY;//服务器IP地址--允许连接到所有本地地址上 my_addr.sin_port=htons(8000); //服务器端口号 /*创建服务器端套接字--IPv4协议,面向无连接通信,UDP协议*/ if((server_sockfd=socket(PF_INET,SOCK_DGRAM,0))<0) { perror("socket error"); return 1; } /*将套接字绑定到服务器的网络地址上*/ if (bind(server_sockfd,(struct sockaddr *)&my_addr,sizeof(struct sockaddr))<0) { perror("bind error"); return 1; } sin_size=sizeof(struct sockaddr_in); printf("waiting for a packet.../n"); /*接收客户端的数据并将其发送给客户端--recvfrom是无连接的*/ if((len=recvfrom(server_sockfd,buf,BUFSIZ,0,(struct sockaddr *)&remote_addr,&sin_size))<0) { perror("recvfrom error"); return 1; } printf("received packet from %s:/n",inet_ntoa(remote_addr.sin_addr)); buf[len]='/0'; printf("contents: %s/n",buf); /*关闭套接字*/ close(server_sockfd); return 0; }
linux下UDP客户端代码
#include <stdio.h>#include <sys/types.h>#include <sys/socket.h>#include <netinet/in.h>#include <arpa/inet.h> int main(int argc, char *argv[]) { int client_sockfd; int len; struct sockaddr_in remote_addr; //服务器端网络地址结构体 int sin_size; char buf[BUFSIZ]; //数据传送的缓冲区 memset(&remote_addr,0,sizeof(remote_addr)); //数据初始化--清零 remote_addr.sin_family=AF_INET; //设置为IP通信 remote_addr.sin_addr.s_addr=inet_addr("127.0.0.1");//服务器IP地址 remote_addr.sin_port=htons(8000); //服务器端口号 /*创建客户端套接字--IPv4协议,面向无连接通信,UDP协议*/ if((client_sockfd=socket(PF_INET,SOCK_DGRAM,0))<0) { perror("socket error"); return 1; } strcpy(buf,"This is a test message"); // 发送的内容 printf("sending: '%s'/n",buf); sin_size=sizeof(struct sockaddr_in); /*向服务器发送数据包*/ if((len=sendto(client_sockfd,buf,strlen(buf),0,(struct sockaddr *)&remote_addr,sizeof(struct sockaddr)))<0) { perror("recvfrom"); return 1; } /*关闭套接字*/ close(client_sockfd); return 0; }
最后说一句啦。本网络编程入门系列博客是连载学习的,有兴趣的可以看我博客其他篇。。。。
参考博客:https://blog.csdn.net/u012234115/article/details/54142273
参考博客:https://www.cnblogs.com/zwj-199306231519/p/9067618.html
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦