UDP连接代码

由于只有部分代码,自己填不上.......程序未能运行成功,悲剧!

server:

 1 SOCKET s = ::socket(AF_INET,SOCK_DGRAM,IPPROTO_TCP);
 2      if(s == INVALID_SOCKET)
 3      {
 4          printf("Failed socket()\n");
 5          return 0;
 6      }
 7      //填充sockaddr_in结构
 8      sockaddr_in sin;
 9      sin.sin_family = AF_INET;
10      sin.sin_port = htons(4567);
11      sin.sin_addr.S_un.S_addr = INADDR_ANY;
12      //绑定这个套接字的一个本地地址
13      if(::bind(s,(LPSOCKADDR)&sin,sizeof(sin)) == SOCKET_ERROR)
14      {
15          printf("Failed bind()\n");
16          return 0;
17      }
18      //进入监听模式
19      if(::listen(s,2) == SOCKET_ERROR)
20      {
21          printf("Failed listen()\n");
22          return 0;
23      }
24      //接收数据
25      char buff[1024];
26      sockaddr_in addr;
27      int nLen = sizeof(addr);
28      while(TRUE)
29      {
30          int nRecv = ::recvfrom(s,buff,1024,0,(sockaddr*)&addr,&nLen);
31          if(nRecv > 0)
32          {
33              buff[nRecv] = '\0';
34              printf("接收到数据 (%s):%s",::inet_ntoa(addr.sin_addr),buff);
35          }
36      }
37      ::closesocket(s);

client:

1 sockaddr_in addr;
2      addr.sin_family=AF_INET;
3      addr.sin_port=htons(4567);
4      addr.sin_addr.S_un.S_addr=inet_addr("49.140.16.244");
5      //发送数据
6      char szText[] = "TCP Server Demo!\r\n";
7      ::sendto(s,szText,strlen(szText),0,(sockaddr*)&addr,sizeof(addr));

只能这样了,日后再说

posted @ 2012-10-08 23:17 xingoo 阅读(...) 评论(...) 编辑 收藏