斜树的空间

集中精力,放弃一切的去做一件事情,只要尽力了,即使失败了,你也不会后悔!

  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  47 随笔 :: 0 文章 :: 12 评论 :: 0 Trackbacks

使用协议UDP,仅实现简单的连接功能:

服务端:
#pragma   comment(lib,   "ws2_32.lib ")

#include <winsock2.h>
#include <stdio.h>

int main()
{
 SOCKET socket1;
 WSADATA wsaData;


 int iErrorcode;
 if(WSAStartup(MAKEWORD(2,2), &wsaData))
 {
  printf("Winsock can not be init!");
  WSACleanup();
  return 0;
 }

 printf("server begin to create socket!\n");
 //struct sockaddr_in local;
 //struct sockaddr_in from;
 sockaddr_in local;
 sockaddr_in from;

 int fromlen = sizeof(from);

 local.sin_addr.s_addr = INADDR_ANY;
 local.sin_family =  AF_INET;
 local.sin_port = htons(5566);

 socket1 = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
 bind(socket1, (struct sockaddr *)&local, fromlen);
 
 while(1)
 {
  char buffer[1024] = "\0";

  printf("waiting message form client:");

  if(SOCKET_ERROR != recvfrom(socket1,
   buffer, sizeof(buffer), 0,
   (struct sockaddr *)&from, &fromlen))
  {
   if(strcmp(buffer, "bye") == 0)
   {
    printf("client quit!\n");
    break;
   }
   printf("recieve message form %s -- %s \n",
    inet_ntoa(from.sin_addr), buffer);
   sendto(socket1, buffer, sizeof(buffer),
    0, (struct sockaddr *)&from, fromlen);
  }
  
 }
 closesocket(socket1);

 return 0;
}

客户端:
#pragma   comment(lib,   "ws2_32.lib ")

#include <winsock2.h>
#include <stdio.h>

int main()
{
 SOCKET socket1;
 WSADATA wsaData;

 if(WSAStartup(MAKEWORD(2,2), &wsaData))
 {
  printf("can not init !\n");
  WSACleanup();
  return 0;
 }
 
 printf("client begin to create socket!\n");
 struct sockaddr_in server;
 int len = sizeof(server);

 server.sin_addr.s_addr = inet_addr("127.0.0.1");
 server.sin_port = htons(5566);
 server.sin_family = AF_INET;

 socket1 = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP );
 
 while(1)
 {
  char buffer[1024] = "\0";
  printf("input message: ");
  scanf("%s", buffer);
  if(strcmp(buffer, "bye") == 0)
  {
   sendto(socket1, "bye", 3 * sizeof(char), 0,
    (struct sockaddr *)&server, len);
   printf("exit!\n");
   Sleep(100);
   closesocket(socket1);
   break;
  }
  
  if(SOCKET_ERROR != sendto(socket1, buffer, sizeof(buffer),
   0, (sockaddr *)&server, len))
  {
   Sleep(100);
   if(recvfrom(socket1, buffer, sizeof(buffer), 0, (struct sockaddr *)&server, &len) != SOCKET_ERROR)
   {
    printf("recieve from server : %s \n", buffer);
   }
  }
  
 }
 closesocket(socket1);

 return 0;
}

posted on 2010-05-15 21:12 张贵川 阅读(666) 评论(0)  编辑 收藏 引用

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理