双管齐下--Windows和Linux下面的Socket网络通信

    技术2022-06-08  37

    Windows和Linux下面的Socket网络通信,流程都是一样的,如下:   =>基于TCP的socket编程  ----------------------------------------------------------------------------------   服务器端程序                                      |                          客户端程序  ----------------------------------------------------------------------------------                                                          |  1. 创建套接字 (socket)                         |   1. 创建套接字 (socket)                                                          |  2. 将套接字绑定到一个本地地址和             |   2. 向服务器发出连接请求 (connect)  端口上 (bind)                                      |                                                          |   3. 与服务器端进行通信 (send/recv)  3. 将套接字设置为监听模式,准备               |   接收客户请求 (listen)                            |   4. 关闭套接字                                                          |   4. 等待客户请求;请求到来,接受                |   连接请求,返回新的对应此次连接                |  的套接字 (accept)                                |                                                          |   5. 用返回的套接字和客户端进行                |   通信 (send/recv)                                 |                                                          |  6. 返回,等待另一个客户请求                    |                                                           |  7. 关闭套接字                                      |  ----------------------------------------------------------------------------------Linux代码:服务端:

    [code] /*********************************************************** *AUTHOR: Penny House * *DATE: 2011-04-02 13:39:23 * *DESCRIPTION: server * ************************************************************/ #include <stdio.h> #include <stdlib.h> #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #include <string.h> #include <time.h> #include <sys/wait.h> #include <signal.h> #include <sys/select.h> #include <fcntl.h> //#define __DEBUG__ #define NORMAL 0 #define EXCEPTION -1 static int gnSrvSock; static int gnCliSock; static struct sigaction gstruAct; static struct sigaction gstruOldAct; void CaptureQuitSignal() { printf("[WARNING] SIGINT signal!/n"); kill(0,SIGINT); /**/ if(sigaction(SIGINT,&gstruOldAct,NULL)==-1) printf("[ERRORS] set struOldAct is failed!/n"); printf("[INFO] struOldAct reset OK!/n"); /**/ close(gnSrvSock); close(gnCliSock); printf("[INFO] close socket OK!/n"); printf("-----------------------Quit!/n"); exit(0); } int SetSignal() { memset(&gstruOldAct,0,sizeof(gstruOldAct)); memset(&gstruAct,0,sizeof(gstruAct)); gstruAct.sa_handler=CaptureQuitSignal; gstruAct.sa_flags=0; sigfillset(&gstruAct.sa_mask); if(sigaction(SIGINT,&gstruAct,&gstruOldAct)==-1) { printf("[ERRORS] sigaction is failed!/n"); return EXCEPTION; } return NORMAL; } void SetSock() { int nStatus=0; if((nStatus=fcntl(gnSrvSock,F_GETFL,0))==-1) { printf("[WARNING] get socket failed!/n"); } nStatus|=O_NONBLOCK; if(fcntl(gnSrvSock,F_SETFL,nStatus)==-1) { printf("[WARNING] set socket failed!/n"); } } void InitSrvSock(struct sockaddr_in *pstruSrv) { pstruSrv->sin_family=AF_INET; pstruSrv->sin_addr.s_addr=inet_addr("172.25.27.116"); pstruSrv->sin_port=htons(9734); } int CreateSocket(struct sockaddr_in *pstruIn) { int nComSock; nComSock=socket(AF_INET,SOCK_STREAM,0); bind(nComSock,(struct sockaddr *)pstruIn,sizeof(struct sockaddr_in)); listen(nComSock,5); return nComSock; } int StartChildProc() { int nByte=0; char szWriteBuff[1024]; char szReadBuff[1024]; memset(szWriteBuff,0,sizeof(szWriteBuff)); memset(szReadBuff,0,sizeof(szReadBuff)); strcpy(szWriteBuff,"TEXT SENDING INFORMATION!/n"); while(1) { if(gnCliSock<0) { printf("[ERROR] Invaild client socket handle!/n"); return EXCEPTION; } nByte=read(gnCliSock,szReadBuff,sizeof(szReadBuff)); if(nByte==0) { printf("[ERRORS] read from client socket failed!/n"); return EXCEPTION; } printf("Client:%s/n",szReadBuff); nByte=0; memset(szReadBuff,0,sizeof(szReadBuff)); usleep(5000000); nByte=write(gnCliSock,szWriteBuff,sizeof(szWriteBuff)); if(nByte==0) { printf("[ERRORS] write to client socket failed!/n"); return EXCEPTION; } usleep(5000000); } } int main(int argc,char *argv[]) { int nPid; int nLen; int nByte; fd_set fset; char szWriteBuff[1024]; char szReadBuff[1024]; struct timeval struTimeout; struct sockaddr_in struSrvAddr; struct sockaddr_in struCliAddr; nByte=0; nLen=sizeof(struCliAddr); memset(szWriteBuff,0,sizeof(szWriteBuff)); memset(szReadBuff,0,sizeof(szReadBuff)); if(SetSignal()==EXCEPTION) { printf("[ERRORS] set signal failed!/n"); return EXCEPTION; } InitSrvSock(&struSrvAddr); if((gnSrvSock=CreateSocket(&struSrvAddr))<0) { printf("[ERRORS]create socket failed!/n"); return EXCEPTION; } // SetSock(); while(1) { FD_ZERO(&fset); FD_SET(gnSrvSock,&fset); struTimeout.tv_sec=5; struTimeout.tv_usec=0; #ifdef __DEBUG__ select(gnSrvSock,&fset,NULL,NULL,&struTimeout); if(FD_ISSET(gnSrvSock,&fset)) { printf("[INFO] client connected!/n"); gnCliSock=accept(gnSrvSock,(struct sockaddr*)&struCliAddr,&nLen); /**/ nPid=fork(); switch(nPid) { case -1: printf("[WARNING] fork failed!/n"); continue; break; case 0: printf("[INFO] handle client connection!/n"); StartChildProc(); break; default: printf("-------------------father reporting!/n"); break; } } printf("[WARNING] timeout! no socket connected!/n"); #else printf("[INFO] client connected!/n"); gnCliSock=accept(gnSrvSock,(struct sockaddr*)&struCliAddr,&nLen); strcpy(szWriteBuff,"TEXT SENDING INFORMATION!/n"); while(1) { if(gnCliSock<0) { printf("[ERROR] Invaild client socket handle!/n"); return EXCEPTION; } nByte=read(gnCliSock,szReadBuff,sizeof(szReadBuff)); if(nByte==0) { printf("[ERRORS] read from client socket failed!/n"); return EXCEPTION; } printf("Client:%s/n",szReadBuff); nByte=0; memset(szReadBuff,0,sizeof(szReadBuff)); usleep(500000); nByte=write(gnCliSock,szWriteBuff,sizeof(szWriteBuff)); if(nByte==0) { printf("[ERRORS] write to client socket failed!/n"); return EXCEPTION; } usleep(500000); } #endif } return NORMAL; } [/code] 客户端: [code] /*********************************************************** *AUTHOR: Penny House * *DATE: 2011-04-02 13:39:23 * *DESCRIPTION: client * ************************************************************/ #include <stdio.h> #include <stdlib.h> #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #include <string.h> #include <time.h> #include <sys/wait.h> #include <signal.h> #include <sys/select.h> #include <fcntl.h> #define NORMAL 0 #define EXCEPTION -1 static int gnCommSock; static struct sigaction gstruAct; static struct sigaction gstruOldAct; void CaptureQuitSignal() { printf("[WARNING] SIGINT signal!/n"); kill(0,SIGINT); /**/ if(sigaction(SIGINT,&gstruOldAct,NULL)==-1) printf("[ERRORS] set gstruOldAct is failed!/n"); printf("[INFO] gstruOldAct reset OK!/n"); /**/ close(gnCommSock); printf("[INFO] close socket OK!/n"); printf("-----------------------Quit!/n"); exit(0); } int SetSignal() { memset(&gstruOldAct,0,sizeof(gstruOldAct)); memset(&gstruAct,0,sizeof(gstruAct)); gstruAct.sa_handler=CaptureQuitSignal; gstruAct.sa_flags=0; sigfillset(&gstruAct.sa_mask); if(sigaction(SIGINT,&gstruAct,&gstruOldAct)==-1) { printf("[ERRORS] sigaction is failed!/n"); return EXCEPTION; } return NORMAL; } int SetSocket(struct sockaddr_in *pstruAddr,char *pszSrvIP,int nPort) { pstruAddr->sin_family=AF_INET; pstruAddr->sin_addr.s_addr=inet_addr(pszSrvIP); pstruAddr->sin_port=htons(nPort); return NORMAL; } int main(int argc,char *argv[]) { int nPid; int nFlag; int nPort; int nCount; char szSendBuff[1024]; char szRecvBuff[1024]; struct sockaddr_in struConAddr; nCount=0; nFlag=-1; nPort=atoi(argv[2]); memset(&struConAddr,0,sizeof(struConAddr)); memset(szSendBuff,0,sizeof(szSendBuff)); memset(szRecvBuff,0,sizeof(szRecvBuff)); if(argc<3) { printf("[ERRORS] argc<3!/n/tExample:./client IP Port/n"); return EXCEPTION; } printf("IP:%s/tPORT:%s/n",argv[1],argv[2]); SetSignal(); SetSocket(&struConAddr,argv[1],nPort); gnCommSock=socket(AF_INET,SOCK_STREAM,0); if(gnCommSock<0) { printf("[ERRORS] create socket failed!/n"); return EXCEPTION; } printf("connecting....../n"); if(connect(gnCommSock,(struct sockaddr*)&struConAddr,sizeof(struConAddr))<0) { printf("[ERRORS] connect to server failed!/n"); return EXCEPTION; } strcpy(szSendBuff,"CLIENT REPORTING!/n"); printf("Loop Working....../n"); while(1) { nCount=write(gnCommSock,szSendBuff,sizeof(szSendBuff)); if(nCount==0) { printf("[WARNING] write to server failed!/n"); } nCount=0; usleep(500000); nCount=read(gnCommSock,szRecvBuff,sizeof(szRecvBuff)); if(nCount==0) { printf("[WARNING] read from server failed!/n"); } printf("Server:%s/n",szRecvBuff); memset(szRecvBuff,0,sizeof(szRecvBuff)); usleep(500000); } return NORMAL; } [/code]

     

     

     

    Windows代码(VC++6.0):服务端:

    //------------------------------------------------------------------------ #include <Winsock2.h> #include <stdio.h> void main() { WORD wVersionRequested; WSADATA wasDATA; int err; wVersionRequested=MAKEWORD(1,1); err=WSAStartup(wVersionRequested,&wasDATA); if (err!=0) { return; } if (LOBYTE(wasDATA.wVersion)!=1||HIBYTE(wasDATA.wVersion)!=1) { WSACleanup(); return; } //创建套接字 SOCKET sockSrv=socket(AF_INET,SOCK_STREAM,0); SOCKADDR_IN addrSrv; addrSrv.sin_addr.S_un.S_addr=htonl(INADDR_ANY); // 套接字的主机IP地址 addrSrv.sin_family=AF_INET; addrSrv.sin_port=htons(5800); //绑定套接字 bind(sockSrv,(SOCKADDR *)&addrSrv,sizeof(addrSrv)); //监听模式 listen(sockSrv,5); //循环等待客户端请求 SOCKADDR_IN addrClient; // 存放客户端的地址信息 int len=sizeof(SOCKADDR); while (1) { //创建连接 SOCKET sockConn=accept(sockSrv,(SOCKADDR *)&addrClient,&len); //发送信息 char sendBuf[100]; sprintf(sendBuf,"Welcom %s to WebSock!",inet_ntoa(addrClient.sin_addr)); send(sockConn,sendBuf,sizeof(sendBuf)+1,0); //接收数据 char recvBuf[100]; recv(sockConn,recvBuf,100,0); printf("%s/n",recvBuf); //关闭套接字 closesocket(sockConn); } }

    客户端:#include <Winsock2.h> #include <stdio.h> void main() { WORD wVersionRequested; WSADATA wasDATA; int err; wVersionRequested=MAKEWORD(1,1); err=WSAStartup(wVersionRequested,&wasDATA); if (err!=0) { return; } if (LOBYTE(wasDATA.wVersion)!=1||HIBYTE(wasDATA.wVersion)!=1) { WSACleanup(); return; } //创建套接字 SOCKET sockClient; sockClient=socket(AF_INET,SOCK_STREAM,0); //连接服务器端 SOCKADDR_IN addrSrv; addrSrv.sin_addr.S_un.S_addr=inet_addr("127.0.0.1"); addrSrv.sin_family=AF_INET; addrSrv.sin_port=htons(5800); connect(sockClient,(SOCKADDR *)&addrSrv,sizeof(SOCKADDR)); //接收消息 char recvBuf[100]; recv(sockClient,recvBuf,100,0); printf("%s/n",recvBuf); //发送消息 send(sockClient,"This is Client One!",strlen("This is Client One!")+1,0); //关闭套接字 closesocket(sockClient); WSACleanup(); }


    最新回复(0)