socket 编程

照抄自:罗莉琴等《windows 网络编程》
在测试的时候可能会遇到,自己电脑上可以运行的server.exe或client.exe 在别人电脑上报错“缺少msvcr100d.dll”。解决方式是:http://blog.csdn.net/stormbjm/article/details/23376249

server 端:

#include "stdafx.h"
#include 
#include 
#include
#pragma comment (lib,"WS2_32.lib")

#define BUF_SIZE 64

int _tmain(int argc, _TCHAR* argv[])
{   
    WSADATA wsd;
    SOCKET sServer;//用于监听客户端请求
    SOCKET sClient;//用于实现与客户端的通信
    int retVal;
    char buf[BUF_SIZE];

    //初始化Socket动态库
    if(WSAStartup(MAKEWORD(2,2),&wsd)!=0)
    {
        printf("WSAStarup failed!\n");
    }

    //创建socket
    sServer = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
    if(INVALID_SOCKET==sServer)
    {
        printf("socket failed!\n");
        WSACleanup();
        return -1;
    }

    //设置服务器socket地址
     SOCKADDR_IN addrServ;
     addrServ.sin_family = AF_INET;
     addrServ.sin_port = htons(50000);
     addrServ.sin_addr.S_un.S_addr = htonl(INADDR_ANY);

     //绑定socket与本地监听地址
     retVal = bind(sServer,(const struct sockaddr*)&addrServ,sizeof(SOCKADDR_IN));
     if(SOCKET_ERROR==retVal)
     {
         printf("bind failed!\n");
         closesocket(sServer);
         WSACleanup();
         return -1;
     }

     //进行监听
     retVal=listen(sServer,1);
     if(SOCKET_ERROR == retVal)
     {
         printf("listen failed!\n");
         closesocket(sServer);
         WSACleanup();
         return -1;
     }

     //接收来自客户端的请求
     printf("TCP Server start...\n");
     sockaddr_in addrClient;
     int addrClientlen = sizeof(addrClient);
     sClient = accept(sServer,(sockaddr FAR*)&addrClient,&addrClientlen);
      if(INVALID_SOCKET == sClient)
     {
         printf("accept failed!\n");
         closesocket(sServer);
         WSACleanup();
         return -1;
     }

      //在服务器与客户端之间发送和接收数据
      //循环接收客户端数据,直到客户端发出quit命令后退出
      while(true)
      {
      ZeroMemory(buf,BUF_SIZE);
      retVal=recv(sClient,buf,BUF_SIZE,0);
       if(SOCKET_ERROR == retVal)
     {
         printf("recv failed!\n");
         closesocket(sServer);
         closesocket(sClient);
         WSACleanup();
         return -1;
     }
       //获取当前系统时间
       SYSTEMTIME st;
       GetLocalTime(&st);
       char sDataTime[30];
       sprintf(sDataTime,"%4d-%2d-%2d %2d:%2d:%2d",st.wYear,st.wMonth,st.wDay,st.wHour,st.wMinute,st.wSecond);
       printf("%s,Recv From Client[%s:%d]:%s\n",sDataTime,inet_ntoa(addrClient.sin_addr),addrClient.sin_port,buf);

       //如果客户端发送quit字符串,则退出。
       if(strcmp(buf,"quit")==0)
       {
           retVal = send(sClient,"quit",strlen("quit"),0);
           break;
       }//否则向客户端发送回显字符串
       else 
       {
           char msg[BUF_SIZE];
           sprintf(msg,"Message received - %s",buf);
           retVal = send(sClient,msg,strlen(msg),0);
           if(SOCKET_ERROR==retVal)
           {
               printf("send failed!\n");
               closesocket(sServer);
               closesocket(sClient);
               WSACleanup();
               return -1;
           }
       }
      }

      //释放socket
      closesocket(sServer);
      closesocket(sClient);
      WSACleanup();
      system("pause");
      return 0;
}

client 端

#include "stdafx.h"
#include
#include //程序中使用到 std::string
#include
#include
#pragma comment(lib,"WS2_32.lib")

#define BUF_SIZE 64 //缓冲区大小

int _tmain(int argc,_TCHAR* argv[])
{
    WSADATA wsd;    //用于初始化
    SOCKET sHost;   //与服务器通信的socket
    SOCKADDR_IN servAddr;   //服务器地址
    char buf[BUF_SIZE];
    int retVal;         //调用各种socket函数的返回值

    //初始化socket动态库
    if(WSAStartup(MAKEWORD(2,2),&wsd)!=0)
    {
        printf("WSAStartup failed!\n");
        return 1;
    }

    //创建socket
    sHost = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
    if(INVALID_SOCKET==sHost)
    {
        printf("socket failed \n");
        WSACleanup();
        return -1;
    }

    //设置服务器地址
    servAddr.sin_family =AF_INET;
    //用户根据需要实际情况修改
    servAddr.sin_addr.S_un.S_addr=inet_addr("10.160.31.53");
    //在实际应用中,建议将服务器的IP地址和端口号保存在配置文件中。

    servAddr.sin_port=htons(50000);
    //计算地址长度
    int sServerAddlen = sizeof(servAddr);

    //连接到服务器
    retVal = connect(sHost,(LPSOCKADDR)&servAddr,sizeof(servAddr));
    if(SOCKET_ERROR==retVal)
    {
        printf("connect failed!\n");
        closesocket(sHost);
        WSACleanup();
        return -1;
    }

    //循环向服务器发送字符串,并显示反馈信息
    //发送“quit”将使服务器程序退出,同时客户端程序自身也将退出
    while(true)
    {
        //向服务器发送数据
        printf("Please input a string to send:");
        std::string str;
        //接收输入的数据
        std::getline(std::cin,str);
        //将用户输入的数据赋值到buf中
        ZeroMemory(buf,BUF_SIZE);
        strcpy(buf,str.c_str());
        //向服务器发送数据
        retVal = send(sHost,buf,strlen(buf),0);
        if(SOCKET_ERROR==retVal)
    {
        printf("send failed!\n");
        closesocket(sHost);
        WSACleanup();
        return -1;
    }
        //接收服务器回传的数据
        retVal = send(sHost,buf,sizeof(buf),0);
        printf("Recv From Server: %s\n",buf);

        //如果收到“quit”,则退出
        if(strcmp(buf,"quit")==0)
        {
            printf("quit!\n");
            break;
        }
    }
    //释放资源
    closesocket(sHost);
    WSACleanup();
    system("pause");
    return 0;
}

你可能感兴趣的:(c语言)