c++ socket 重连
时间: 2023-11-29 16:06:10 浏览: 70
以下是C++ socket重连的示例代码:
```cpp
#include "stdafx.h"
#include <iostream>
#include <string>
#include <Windows.h>
#include <Winsock2.h>
#include <fstream>
#pragma comment(lib,"Ws2_32.lib")
using namespace std;
int main()
{
WSADATA wsaData;
SOCKET clientSocket;
SOCKADDR_IN serverAddr;
char recvBuf[500];
int byteRecv;
int connectState;
// 初始化Winsock
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
cout << "WSAStartup failed!" << endl;
return 1;
}
// 创建socket
clientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (clientSocket == INVALID_SOCKET) {
cout << "Create socket failed!" << endl;
WSACleanup();
return 1;
}
// 设置服务器地址
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(1234);
serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
// 连接服务器
connectState = connect(clientSocket, (SOCKADDR*)&serverAddr, sizeof(serverAddr));
if (connectState == SOCKET_ERROR) {
cout << "Connect failed with error code: " << GetLastError() << endl;
WSACleanup();
return 1;
}
else {
cout << "Connect successfully!" << endl;
}
// 接收消息
byteRecv = recv(clientSocket, recvBuf, 500, 0);
recvBuf[byteRecv] = 0;
cout << recvBuf << endl;
// 关闭socket
closesocket(clientSocket);
// 重新连接
clientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (clientSocket == INVALID_SOCKET) {
cout << "Create socket failed!" << endl;
WSACleanup();
return 1;
}
connectState = connect(clientSocket, (SOCKADDR*)&serverAddr, sizeof(serverAddr));
if (connectState == SOCKET_ERROR) {
cout << "Reconnect failed with error code: " << GetLastError() << endl;
WSACleanup();
return 1;
}
else {
cout << "Reconnect successfully!" << endl;
}
// 接收消息
byteRecv = recv(clientSocket, recvBuf, 500, 0);
recvBuf[byteRecv] = 0;
cout << recvBuf << endl;
// 关闭socket
closesocket(clientSocket);
// 清理Winsock
WSACleanup();
return 0;
}
```
阅读全文