Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1151060
  • 博文数量: 222
  • 博客积分: 5262
  • 博客等级: 大校
  • 技术积分: 3028
  • 用 户 组: 普通用户
  • 注册时间: 2009-11-22 19:10
文章分类

全部博文(222)

文章存档

2012年(2)

2011年(192)

2010年(28)

分类: WINDOWS

2011-03-12 12:29:05

UDP windows下socket编程实例 Server 端程序源代码:

#include

#include

void main()

{

SOCKET socket1;

WSADATA wsaData;

     int iErrorCode;

     if (WSAStartup(MAKEWORD(2,1),&wsaData)) //调用Windows Sockets DLL

     {

          printf("Winsock无法初始化!\n");

          WSACleanup();

          return;

     }

 printf("服务器开始创建SOCKET。\n");

struct sockaddr_in local;

struct sockaddr_in from;

int fromlen =sizeof(from);

local.sin_family=AF_INET;

local.sin_port=htons(27015); ///监听端口

local.sin_addr.s_addr=INADDR_ANY; ///本机

socket1=socket(AF_INET,SOCK_DGRAM,0);

bind(socket1,(struct sockaddr*)&local,sizeof(local));

while (1)

{

char buffer[1024]="\0";

printf("waiting for message from others-------------\n");

if (recvfrom(socket1,buffer,sizeof(buffer),0,(struct sockaddr*)

&from,&fromlen)!=SOCKET_ERROR)

{

printf("Received datagram from %s--%s\n",inet_ntoa(from.sin_addr),buffer);

////给cilent发信息

sendto(socket1,buffer,sizeof(buffer),0,(struct sockaddr*)&from,fromlen);

 

 

}

//Sleep(1000);

}

closesocket(socket1);

}

 

注意:

error   LNK2001一般都是因为没有连接.lib或者连接的.lib中没有你调用的函数

如下解决:

[Project->Setting]->[Link->Object/Library   modules]加入Ws2_32.lib 就好了。

Client端源代码:

#include

#include

void main()

{

SOCKET socket1;

WSADATA wsaData;

     int iErrorCode;

     if (WSAStartup(MAKEWORD(2,1),&wsaData)) //调用Windows Sockets DLL

     {

          printf("Winsock无法初始化!\n");

          WSACleanup();

          return;}

printf("服务器开始创建SOCKET。\n");

struct sockaddr_in server;

int len =sizeof(server);

server.sin_family=AF_INET;

server.sin_port=htons(27015); ///server的监听端口

server.sin_addr.s_addr=inet_addr("221.223.16.32"); ///server的地址

socket1=socket(AF_INET,SOCK_DGRAM,0);

while (1)

{

     char buffer[1024]="\0";

     printf("input message\n");

     scanf("%s",buffer);

     if (strcmp(buffer,"bye")==0)

     {

         printf("退出!\n");

         Sleep(100);

         closesocket(socket1);

         break;

     }

     if (sendto(socket1,buffer,sizeof(buffer),0,(struct sockaddr*)

&server,len)!=SOCKET_ERROR)

     {

         //printf("sending..\n");

         Sleep(100);

         if (recvfrom(socket1,buffer,sizeof(buffer),0,(struct sockaddr*)

&server,&len) != SOCKET_ERROR)

         printf("rece from server:%s\n",buffer);

     }    }

     closesocket(socket1);

}

阅读(1480) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~