资源描述:
《网络接口编程-聊天,广播程序》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、广播:接收程序#include#include#include#pragmacomment(lib,"ws2_32.lib")voidmain(void){SOCKETs;sockaddr_infrom,a;WSADATAwsdata;BOOLoptval;//启动SOCKET库,版本为2.0WSAStartup(WINSOCK_VERSION,&wsdata);optval=TRUE;//然后赋值给两个地址,一个用来绑定套接字,一个用来从网络上的广播地址接收
2、消息;a.sin_family=AF_INET;a.sin_addr.s_addr=INADDR_ANY;a.sin_port=htons(9999);from.sin_family=AF_INET;from.sin_addr.s_addr=INADDR_BROADCAST;from.sin_port=htons(9999);intfromlength=sizeof(SOCKADDR);//用UDP初始化套接字s=socket(AF_INET,SOCK_DGRAM,0);//设置该套接字为广播类型,setsockopt(s
3、,SOL_SOCKET,SO_BROADCAST,(charFAR*)&optval,sizeof(optval));bind(s,(sockaddr*)&a,sizeof(sockaddr_in));charbuf[256];while(1){//从广播地址接收消息,注意用来绑定的地址和接收消息的地址是不一样的recvfrom(s,buf,256,0,(structsockaddrFAR*)&from,(intFAR*)&fromlength);Sleep(2000);printf("%s",buf);ZeroMem
4、ory(buf,256);memset(&buf,0,sizeof(buf));}}发送程序:#include#include#include#pragmacomment(lib,"ws2_32.lib")main(){SOCKETs;sockaddr_inaddrto;WSADATAwsdata;BOOLbsocket;char*smsg="你好!这是广播测试!";WSAStartup(WINSOCK_VERSION,&wsdata);s=WSASocket
5、(AF_INET,SOCK_DGRAM,0,NULL,0,WSA_FLAG_OVERLAPPED);bsocket=TRUE;//然后赋值给地址,用来从网络上的广播地址接收消息;memset(&addrto,0,sizeof(addrto));addrto.sin_family=AF_INET;addrto.sin_addr.s_addr=INADDR_BROADCAST;addrto.sin_port=htons(9999);boolopt=true;//设置该套接字为广播类型,setsockopt(s,SOL_SOCK
6、ET,SO_BROADCAST,(charFAR*)&opt,sizeof(opt));intnlen=sizeof(addrto);while(1){Sleep(2000);//从广播地址发送消息intret=sendto(s,smsg,256,0,(sockaddr*)&addrto,nlen);if(ret==SOCKET_ERROR)printf("Senderror%d!",WSAGetLastError());else{printf("广播发送成功");}}}服务器端程序:1、创建套接字(socket)
7、2、将socket绑定到一个本地IP地址和端口上(bind)3、将socket设为监听模式,准备接收客户请求(listen)4、等待客户请求到来:当请求到来后,接收连接请求,返回一个新的对应于此次连接的socket(accept)5、用返回的socket和客户端进行通信(send/recv)6、返回,等待另一客户请求7、关闭socket(closesocket)客户端程序:1、创建套接字(socket)2、向服务器发出连接请求(connect)3、和服务器进行通信(send/recv)4、关闭socket(closesoc
8、ket)#include“iostream.h”#include“winsock2.h”#include“windows.h”#defineInternetAddr“127.0.0.1”#defineiPort5055#pragmacomment(lib,“ws2_32.lib”)voidmain(){