基于UDP的通讯
XX:那飘过的100~_~{2014/10/03 10:57}
UDP是一种面向非连接SOCK_DGRAM,提供无连接服务。数据包以独立包形式发送,不提供无措保证,数据能够丢失或反复。
UDP的Server和Client的差别相对照较模糊,仅仅要调用 sendto和 recvfrom 就能够给指定的地址收发数据。
1. server端:
// udpClient.cpp : Defines the entry point for the application. // #include "stdafx.h" #include "tchar.h" #pragma comment(lib,"wsock32.lib") #include <stdio.h> #include <winsock2.h> BOOL InitWinsock(); //Winsock服务初始化 void main() { SOCKET socket1; InitWinsock(); struct sockaddr_in local; struct sockaddr_in from; int err; int fromlean=sizeof(from); local.sin_family=AF_INET; local.sin_port=htons(1234); //监听端口 local.sin_addr.S_un.S_addr=INADDR_ANY; //本机 socket1=socket(AF_INET,SOCK_DGRAM,0); bind(socket1,(sockaddr *)&local,sizeof local); while(true) { char buffer[1024]="\0"; printf("waiting for message from others \n"); err=recvfrom(socket1,buffer,sizeof(buffer),0,(sockaddr *)&from,&fromlean); if(err!=SOCKET_ERROR) { printf("Received from %s--%s\n",inet_ntoa(from.sin_addr),buffer); //给Client发信息 sendto(socket1,buffer,sizeof buffer,0,(sockaddr *)&from,fromlean); } Sleep(500); } closesocket(socket1); } BOOL InitWinsock() { int Error; WORD Version; WSADATA Wsa; Version=MAKEWORD(2,2); Error=WSAStartup(Version,&Wsa); if(Error!=0) { return FALSE; } else { if(LOBYTE(Wsa.wVersion)!=2 || HIBYTE(Wsa.wHighVersion)!=2) { WSACleanup(); return FALSE; } } return TRUE; }
2.client
// udpClient.cpp : Defines the entry point for the application. // #include "stdafx.h" #include "tchar.h" #pragma comment(lib,"wsock32.lib") #include <stdio.h> #include <winsock2.h> BOOL InitWinsock(); //Winsock服务初始化 void main() { SOCKET socket1; InitWinsock(); struct sockaddr_in server; int err; int lean=sizeof(server); server.sin_family=AF_INET; server.sin_port=htons(1234); //服务器的监听端口为1234 server.sin_addr.S_un.S_addr=inet_addr("192.168.1.18"); //设置为本机地址 socket1=socket(AF_INET,SOCK_DGRAM,0); while(true) { char buffer[1024]="\0"; printf("input message \n"); scanf("%s",buffer); if(strcmp(buffer,"bye")==0) { break; } err=sendto(socket1,buffer,sizeof(buffer),0,(sockaddr *)&server,lean); if(err!=SOCKET_ERROR) { err=recvfrom(socket1,buffer,sizeof(buffer),0,(sockaddr *)&server,&lean); if(err!=SOCKET_ERROR) { printf("receive from server:%s\n",buffer); } } } closesocket(socket1); } BOOL InitWinsock() { int Error; WORD Version; WSADATA Wsa; Version=MAKEWORD(2,2); Error=WSAStartup(Version,&Wsa); if(Error!=0) { return FALSE; } else { if(LOBYTE(Wsa.wVersion)!=2 || HIBYTE(Wsa.wHighVersion)!=2) { WSACleanup(); return FALSE; } } return TRUE; }
程序仍然存在非常大的问题,慢慢改动咯!