socket——UDP服務(wù)器
連接不需要
UDP在socket編程中和TCP的不同
UDP是無連接的傳輸,因此并不需要建立連接,不需要監(jiān)聽是否有客戶端發(fā)送連接請(qǐng)求(具體到socket編程中即UDP不需要listen和accept)
UDP采用面向數(shù)據(jù)報(bào)方式的第二個(gè)參數(shù)是SOCK_DGRAM)
UDP可能會(huì)丟包,也不保證數(shù)據(jù)順序性(QQ上有時(shí)候消息在發(fā)送端和接收端的順序不一樣)
UDP收發(fā)數(shù)據(jù)用sendto/recvfrom函數(shù),每次sendto/recvfrom均需指定地址信息(這一點(diǎn)TCP服務(wù)器中在connect/accept時(shí)確定)
UDPshutdown函數(shù)無效
服務(wù)器端程序:
#include#include#include#include#include#include voidusage{printf;}intmain{if{usage;return1;}//創(chuàng)建套接字intsock=socket;if{perror;return1;}int_port=atoi;char*_ip=argv1;structsockaddr_inlocal;local.sin_family=AF_INET;local.sin_port=htons;local.sin_addr.s_addr=inet_addr;//綁定if&local,sizeof)<0){perror;return2;}charbuf1024;structsockaddr_inclient;socklen_tclient_len;while{//接收數(shù)據(jù)ssize_t_size=recvfrom-1,0,&client,&client_len);if{perror;}elseif{printf;}else{printf;}}return0;}
客戶端程序:
#include#include#include#include#include#include voidusage{printf;}intmain{if{usage;return1;}//創(chuàng)建套接字intsock=socket;if{perror;return2;}int_port=atoi;char*_ip=argv1;//remote保存遠(yuǎn)端服務(wù)器的信息structsockaddr_inremote;remote.sin_family=AF_INET;remote.sin_port=htons;remote.sin_addr.s_addr=inet_addr;socklen_tremote_len=sizeof;charbuf1024;while{printf;fgets,stdin);//發(fā)送數(shù)據(jù)ssize_t_size=sendto-1,0,&remote,remote_len);if{perror;}}return0;}
服務(wù)器端運(yùn)行結(jié)果:
運(yùn)行了3個(gè)客戶端結(jié)果:
Tags:連接不需要,socket——UDP服務(wù)器
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場(chǎng),如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。