星期四, 7月 06, 2006

socket of UDP with C

剛剛寫的是TCP而UDP?
UDP有小小的不同在
socket(AF_INET,SOCK_DRGAM,0);
小小的變動

UDP的程式裡面少了list和accept ,TCP因為3方交握,所以龜毛的要確認來方.UDP就不用了,所以資料傳輸容易miss

//--------------------------------------------------------------------------
#include
#pragma comment(lib,"ws2_32")
#include
using namespace std;

int main()
{

WSADATA wsaData;
int iResult = WSAStartup( MAKEWORD(2,2), &wsaData );
if ( iResult != NO_ERROR )
printf("Error at WSAStartup()\n");

sockaddr_in local;
SOCKET s;


local.sin_family=AF_INET;
local.sin_addr.s_addr=inet_addr("127.0.0.1");
local.sin_port=htons(22222);

s=socket(AF_INET,SOCK_DGRAM,0);
bind(s,(SOCKADDR *)&local,sizeof(local));

char buf[1];
int a=sizeof(local);
for(;;)
{
recvfrom(s,buf,sizeof(buf),0,(SOCKADDR *)&local,&a);

sendto(s,"hello",13,0,(SOCKADDR *)&local,a);
}
cout <return 0;
}

沒有留言: