用户登录  |  用户注册
首 页源码下载网络学院最新源码源码排行屏蔽广告
当前位置:新兴网络 > 网络学院 > 编程开发 > VC/MFC

UDP 与 TCP的连接简单例子(服务端/客户端)

减小字体 增大字体 作者:佚名  来源:本站整理  发布时间:2010-05-24 16:05:34

//服务端

C/C++ code复制代码编辑
#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;
}

//客户端:

C/C++ code复制代码编辑
#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;
}

Tags:UDP连接 TCP连接 VC 服务端 客户端

作者:佚名
  • 好的评价 如果您觉得此文章好,就请您
      71%(5)
  • 差的评价 如果您觉得此文章差,就请您
      29%(2)

网络学院评论评论内容只代表网友观点,与本站立场无关!

   评论摘要(共 0 条,得分 0 分,平均 0 分) 查看完整评论