#include<winsock2.h> #include"InitSock.h" #include<windows.h> #include<cstdio> #include<cstdlib> #include<cstring> #pragma comment(lib,"ws2_32.lib") CInitSock InitSock ; #define SERVERPORT 5010 void dg_echo(SOCKET sSockfd , SOCKADDR * pcliaddr, size_t clilen) ; int main(void) { SOCKET sSockfd ; sockaddr_in Servaddr , Cliaddr ; sSockfd = socket(AF_INET,SOCK_DGRAM,0) ; memset(&Servaddr,0,sizeof(Servaddr)) ; memset(&Cliaddr,0,sizeof(Cliaddr)) ; Servaddr.sin_family = AF_INET ; Servaddr.sin_port = htons(SERVERPORT) ; Servaddr.sin_addr.s_addr = htonl(INADDR_ANY) ; bind(sSockfd,(SOCKADDR *)&Servaddr, sizeof(Servaddr)) ; dg_echo(sSockfd,(SOCKADDR*) &Cliaddr ,sizeof(Cliaddr)) ; return 0 ; } void dg_echo(SOCKET sSockfd , SOCKADDR * pcliaddr, size_t clilen) { int n = 0 ; int iSend = 0 ; int len = 0 ; TCHAR szRecvMsg[1024] ; TCHAR szSendMsg[1024] ; for(; ; ) { len = clilen ; n = recvfrom(sSockfd,szRecvMsg,1024,0,pcliaddr,&len) ; szRecvMsg[n] = '\0' ; printf("接收到 %d 字节数据,内容为 %s\n",n , szRecvMsg) ; strcpy(szSendMsg,szRecvMsg) ; iSend = sendto(sSockfd,szSendMsg,strlen(szSendMsg),0,pcliaddr,len) ; printf("发送到 %d 字节数据,内容为 %s\n",iSend,szSendMsg) ; } }
#include<winsock2.h> #include"InitSock.h" #include<windows.h> #include<cstdio> #include<cstdlib> #include<cstring> #pragma comment(lib,"ws2_32.lib") CInitSock InitSock ; #define SERVERPORT 5010 void dg_cli(FILE *fp,SOCKET sockfd, const SOCKADDR * pservaddr, int servlen) ; int main(void) { SOCKET sSockClient ; sockaddr_in Servaddr ; memset(&Servaddr,0,sizeof(Servaddr)) ; Servaddr.sin_family = AF_INET ; Servaddr.sin_port = htons(SERVERPORT) ; Servaddr.sin_addr.s_addr = inet_addr("127.0.0.1") ; sSockClient = socket(AF_INET,SOCK_DGRAM,0) ; dg_cli(stdin,sSockClient,(SOCKADDR*) &Servaddr,sizeof(Servaddr)) ; return 0 ; } void dg_cli(FILE *fp,SOCKET sockfd, const SOCKADDR * pservaddr, int servlen) { int iRecv = 0 ; int iSend = 0 ; TCHAR szSendMsg[1024] ; TCHAR szRecvMsg[1024] ; while(fgets(szSendMsg,1024,fp) != NULL) { iSend = sendto(sockfd,szSendMsg,strlen(szSendMsg),0,pservaddr,servlen) ; iRecv = recvfrom(sockfd,szRecvMsg,1024,0,NULL,NULL) ; szRecvMsg[iRecv] = '\0' ; printf("回显数据: \n") ; fputs(szRecvMsg,stdout) ; } }