资源描述:
《【精品】电子信息工程类论文.doc》由会员上传分享,免费在线阅读,更多相关内容在工程资料-天天文库。
1、专业:2009级理科实验班姓名:卞佳磊学号:20092113310032实验四使用UDP进行通讯本实验使用2个学时一、实验目的K掌握socket的初始化;2、掌握UDP发送与接收的相关函数;二、实验设备及环境安装VC6.0的主机三、实验步骤WinsockServersocket()A/VSASocket()Ibind()XoIclosesocket0WinsockClientsocket()WSASocket()sendtoOclosesocket()上图就是服务器端和客户端的工作流程。c.exe1、把下面的2个文件udpc.
2、c和udp_s.c分别编译链接成2个程序udp和udp_s.exe.o//udpc.c#include//winsocket2.0的头文件#include#include#defineDEFAUET.PORT5000〃宏定义默认端口#defineBUFFER_LENGTH1024voidmciin(intargc,char*argv[])WSADATAwsaData;intsClient;unsignedshortiPort=DEFAULT_PORT;intiLen
3、;intiSend;charsend_buf[20];charrecv_buf[BUFFER_LENGTH];structsockaddr_inser;〃套接字结构体if(argc<2){printf("Usage:%s[serverIPaddress]",argv[O]);return;}memset(recv_buf,0,sizeof(recv_buf));〃清空接收缓存if(WSAStartup(MAKEWORD(2,2),&wsaData)!=0)〃初始化winsock{printf("FailedtoloadWi
4、nsock!");return;}ser.sin_family=AF_INET;//Internet类型ser.sin_port=htons(iPort);〃端口号ser.sin_addr.s_addr=inet_addr(argv[1]);//IP地址sClient=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);//初始化套接字,使用UDP协议if(sClient==INVALID_SOCKET)〃如果初始化失败{printf("socket()Failed!");return;}wh
5、ile(l){printf(“・>”);gets(send_buf);if(_stricmp(send_buf,"quit")==O)break;iLen=sizeof(ser);iSend=sendto(sClient,send_buf,sizeof(send_buf),OXSOCKADDR*)&ser,iLen);//发送if(iSend==SOCKET_ERROR){printf("sendto()Failed!");}1closesocket(sClient);WSACIeanupO;////////////udp
6、_s.c////////#include#include#defineDEFAUET_PORT5000#defineDATA_BUFFER1024voidmain(){WSADATAwsaData;intsSocket;unsignedshortiPort=DEFAULT_PORT;intiLen,iRecv;charrecvbuf[DATA_BUFFERJ;structsockaddr_inser,cli;printf(H-n);printf("Serverwaiting")
7、;printfC*");if(WSAStartup(MAKEWORD(2,2),&wsaData)!=0){printf("FailedtoloadWinsockAn");return;sSocket=socket(AF_INET,SOCK_DGRAM,0);if(sSocket==INVALID_SOCKET)prins二sockeoFa二CCH=)八return-ser.sinlfami-yuAFIINEHser.sinlpomh〔ons(ipo3.八ser.s5-ladd「.sladdnhcn-(INADDRIA
8、NY)一if(bind(ssockeL(siructsockaddr*)RPsetsizeof(ser)nHSOCKETIERROR)v^aprins.-bindingFa二ed亍--)八recrn八一iLenHsizeof(c=);memser(recvbuf-psize