资源描述:
《socket图片文件传输示例.doc》由会员上传分享,免费在线阅读,更多相关内容在应用文档-天天文库。
1、从前在网上找过很多sock编程的资料,都很高深。。。。对于入门级的我来说,简单又不简陋的小例子更好一些,所以总结一下刚写的小例子,用select模型实现的jpg文件传输,并不完善,只作为今后的一个参考。代码经过调试,应该能用吧。。。。。服务器端:#pragmacomment(lib,"ws2_32.lib")#include#include#defineBUFLENsizeof(buf)intmain(){WSADATAwsaData;SOCKADDR_INseraddr,cliaddr;SOCKETlistensocket,newconne
2、ction,tempsocket;ULONGsockmode;intsockok,totalsock=0;structfd_setfdwrite,fdread;charbuf[10],buf0[10];union{chara[4];intb;}a,flag;a.b=flag.b=0;intcliaddrlen=sizeof(cliaddr);FILE*fp;longcode;intn,he=0,m=0,k=0,b=0;char*p;if(WSAStartup(MAKEWORD(2,0),&wsaData)!=0){printf("error1");return-1;}if((lis
3、tensocket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP))==INVALID_SOCKET){printf("error2");return-1;}seraddr.sin_family=AF_INET;seraddr.sin_port=htons(8889);seraddr.sin_addr.s_addr=inet_addr("127.0.0.1");if(SOCKET_ERROR==bind(listensocket,(SOCKADDR*)&seraddr,sizeof(seraddr))){printf("error3");return
4、-1;}if(SOCKET_ERROR==listen(listensocket,5)){printf("error4");return-1;}printf("waitask");sockmode=1;if(SOCKET_ERROR==ioctlsocket(listensocket,FIONBIO,&sockmode)){printf("erroronioctl");return-1;}if((fp=fopen("output.jpg","rb"))==NULL)//指定的文件是否存在{//指定文件不存在printf("不能打开指定的文件!");}fseek(fp,0,SEE
5、K_END);//读写指针移动到文件结尾k=a.b=ftell(fp);code=htonl(m);//返回当前读写指针的位置,即得到文件长度。p=(char*)&k;while(1){FD_ZERO(&fdread);FD_ZERO(&fdwrite);FD_SET(listensocket,&fdread);for(inti=0;i6、,NULL,NULL))){printf("erroronselect");return-1;}if(FD_ISSET(listensocket,&fdread)){sockok--;if(INVALID_SOCKET==(newconnection=accept(listensocket,(SOCKADDR*)&cliaddr,&cliaddrlen))){printf("error5");return-1;}else{printf("come");totalsock++;tempsocket=newconnection;}if(SOCKET_ERROR==ioctlsocket
7、(newconnection,FIONBIO,&sockmode)){printf("erroronioctl");return-1;}}memset(buf,0,sizeof(buf));//memset(buf0,0,sizeof(buf0));if(FD_ISSET(newconnection,&fdread)){memset(buf,0,sizeof(buf));if(flag.b==2){if(recv(newconnection,flag.a,sizeof