C++ Socket C/S ,实现客户端,服务器端断开重连

// WindowsSocketServer.cpp : 定义控制台应用程序的入口点。
#include "stdafx.h"
#include 
#include 
#include 
#include 
#include 
#pragma comment(lib,"Ws2_32.lib")
using namespace std;
#define PORT 8080
#define IP_ADDRESS "172.16.20.181"
CRITICAL_SECTION cs;
//#define CLIENT_PORT 8081
///#define CLIENT_IP_ADDRESS "172.16.20.181"
//接收每个客户端连接的处理函数
DWORD WINAPI ClientThread(LPVOID lpParameter);
//连接和服务器端有连接的客户端
DWORD WINAPI ConnectClientsThread(LPVOID lpParameter);
  int main(int argc, char* argv[])
  {
      //HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
      //SetConsoleTextAttribute(hConsole,FOREGROUND_GREEN); 
      InitializeCriticalSection(&cs);
      //初始化事件和关键段,自动置位,初始无触发的匿名事件
      //g_hThreadEvent = CreateEvent(NULL,FALSE,FALSE,NULL);
      //system("ipconfig /all >log.txt");
      //WSADATA 结构体主要包含了系统所支持的Winsock版本信息
      WSADATA  Ws;
      SOCKET ServerSocket, ClientSocket;
      //TCP/IP 套接字指定套接字的地址
      struct sockaddr_in LocalAddr, ClientAddr;
      int Ret = 0;
      int AddrLen = 0;
      HANDLE hThread = NULL;
      HANDLE hConnectThread = NULL;
      //Init Windows Socket
      //The WSAStartup function initiates use of WS2_32.DLL by a process.
      //初始化Winsock2.2.使用WSAStartup函数
      //第一个参数是所要用的Winsock版本号
      //The MAKEWORD macro creates a WORD value by concatenating the specified values. 
      //第二个参数就是WSADATA 结构体的指针。如果初始化成功则返回0
      //要注意任何WinsockAPI函数都必须在初始化后使用,包括错误检查函数
      if ( WSAStartup(MAKEWORD(2,2), &Ws) != 0 )
      {
          cout<<"初始化 Socket 失败:"<=0  && line.length() > 0)
             {
                 string clientIp = line.substr(0,index);
                 string clientPort = line.substr(index+1);
                 ClientAddr.sin_family = AF_INET;
                 ClientAddr.sin_addr.s_addr = inet_addr(clientIp.c_str());
                 ClientAddr.sin_port = htons((unsigned short)clientPort.c_str());
                
                 //设置ServerAddr中前8个字符为0x00
                 memset(ClientAddr.sin_zero, 0x00, 8);
                
                 Ret = connect(ServerSocket,(struct sockaddr*)&ClientAddr, sizeof(ClientAddr));
                if( Ret == SOCKET_ERROR )
                {
                    cout<<"服务端的方法 ConnectClients 在 建立与:"<logs.txt\""">";  
          
          Ret = send(ClientSocket, SendBuffer, (int)strlen(SendBuffer), 0);
          if ( Ret == SOCKET_ERROR )
             {
                 cout<<"发送消息失败:"<
#include 
#include 
#include 
#include 
#include 
#include 
#include "tinystr.h"
#include "tinyxml.h"
#pragma comment(lib,"Ws2_32.lib")
using namespace std;
#define PORT 8080
#define IP_ADDRESS "172.16.20.181"
#define LISTEN_PORT 8081
#define LISTEN_IP_ADDRESS "172.16.20.181"
//发送消息结构体
struct SendMsgStruct
{
    SOCKET clientSocket;
    string msg;
    struct sockaddr_in ServerAddr;
};
//接收消息结构体
struct RecvMsgStruct
{
    SOCKET  clientSocket;
    struct sockaddr_in ServerAddr;
};
//发送消息子线程
DWORD WINAPI SendThread(LPVOID lpParameter);
//接收消息子线程
DWORD WINAPI RecvThread(LPVOID lpParameter);
//去除字符串首尾空格
void trim(string &str);
//监听服务器的连接
DWORD WINAPI ListenServerThread(LPVOID lpParameter);
int _tmain(int argc, _TCHAR* argv[])
{
    //HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
    //SetConsoleTextAttribute(hConsole,FOREGROUND_GREEN);
    WSADATA  Ws;
     SOCKET ClientSocket,ServerSocket;
     struct sockaddr_in ServerAddr;
     int Ret = 0;
     int AddrLen = 0;
     HANDLE hThread = NULL;
     HANDLE hSendThread = NULL;
     HANDLE hRevcThread = NULL;
     HANDLE hListenThread = NULL;
     //The WSAStartup function initiates use of WS2_32.DLL by a process.
     //初始化 Windows Socket
     if ( WSAStartup(MAKEWORD(2,2), &Ws) != 0 )
     {
         cout<<"初始化 Socket 失败:"<clientSocket = ClientSocket;
    msgSend->msg = "你好,Msg From Client";
    msgSend->ServerAddr = ServerAddr;
    //传递一个struct
    hSendThread = CreateThread(NULL, 0, SendThread, (LPVOID)msgSend, 0, NULL);
    WaitForSingleObject(hSendThread, INFINITE);
    if( hSendThread == NULL )
    {
        cout<<"创建发送消息子线程失败"<clientSocket = ClientSocket;
    msgRecv->ServerAddr = ServerAddr;
    //传递一个struct指针参数
    hRevcThread = CreateThread(NULL,0,RecvThread,(LPVOID)msgRecv,0,NULL);
    WaitForSingleObject(hRevcThread, INFINITE);
    if( hRevcThread == NULL )
    {
        cout<<"创建接收消息子线程失败"<log.txt");
      //WSADATA 结构体主要包含了系统所支持的Winsock版本信息
      WSADATA  Ws;
      SOCKET ServerSocket, ClientSocket;
      //TCP/IP 套接字指定套接字的地址
      struct sockaddr_in LocalAddr, ServerAddr;
      int Ret = 0;
      int AddrLen = 0;
      HANDLE hThread = NULL;
  
      //初始化Winsock2.2.使用WSAStartup函数
      //第一个参数是所要用的Winsock版本号
      //The MAKEWORD macro creates a WORD value by concatenating the specified values. 
      //第二个参数就是WSADATA 结构体的指针。如果初始化成功则返回0
      //要注意任何WinsockAPI函数都必须在初始化后使用,包括错误检查函数
      if ( WSAStartup(MAKEWORD(2,2), &Ws) != 0 )
      {
          cout<<"初始化 Socket 失败:"<clientSocket;
    string SendMsg = myStruct->msg;
    struct sockaddr_in ServerAddr = myStruct->ServerAddr;
    while( true )
    {    
        int flag = 0;
        int bufSize = SendMsg.length();
        char * buf = const_cast(SendMsg.c_str());
        flag = send(ClientSocket, buf, bufSize, 0);
        //判断当前时候存在可用连接,如果没有,再次连接
        while( flag == -1 || flag == 0)
        {
            cout<<"准备重连"<clientSocket;
    struct sockaddr_in ServerAddr = recvStruct->ServerAddr;
    char recvBuf[500]={"0"}; 
     int byteRecv = recv(clientSocket, recvBuf, 500, 0);
     int connectState;
     while( byteRecv == 0 )
     {
         //连接断开,重连
        cout<<"byteRecv == 0"<


你可能感兴趣的:(C++)