首页 > 代码库 > 基于UDP的通讯
基于UDP的通讯
XX:那飘过的100~_~{2014/10/03 10:57}
UDP是一种面向非连接SOCK_DGRAM,提供无连接服务。数据包以独立包形式发送,不提供无措保证,数据可以丢失或重复。
UDP的Server和Client的区别相对比较模糊,只要调用 sendto和 recvfrom 就可以给指定的地址收发数据。
1. 服务器端:
// 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.客户端
// 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; }
程序仍然存在很大的问题,慢慢修改咯!
基于UDP的通讯
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。