用c++编写一次启动Server端和Client端后,首先由Server端发‘1’给Client端,Client端将接收到的数据加1后,发该数据给Server端,Server端再将数据加1后发给Client端,依次类推。直到Server端收到数据20,Client收到19时,两方中断收发
时间: 2024-03-25 16:35:33 浏览: 104
C++写的客户端与服务端
以下是一个简单的 C++ 代码实现,可以满足你的需求:
Server端:
```cpp
#include <iostream>
#include <WinSock2.h>
#pragma comment(lib, "ws2_32.lib")
using namespace std;
int main()
{
// 初始化 Winsock 库
WSADATA wsaData;
WSAStartup(MAKEWORD(2, 2), &wsaData);
// 创建 Socket
SOCKET serverSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
// 绑定地址和端口
sockaddr_in serverAddr;
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(8888);
serverAddr.sin_addr.S_un.S_addr = INADDR_ANY;
bind(serverSock, (sockaddr*)&serverAddr, sizeof(serverAddr));
// 监听连接请求
listen(serverSock, 1);
// 等待客户端连接
SOCKET clientSock = accept(serverSock, NULL, NULL);
// 发送和接收数据
int dataToSend = 1;
int dataToRecv = 0;
while (dataToSend <= 20 && dataToRecv != 19) {
// 发送数据
send(clientSock, (char*)&dataToSend, sizeof(dataToSend), 0);
cout << "Server sent: " << dataToSend << endl;
// 接收数据
recv(clientSock, (char*)&dataToRecv, sizeof(dataToRecv), 0);
cout << "Server received: " << dataToRecv << endl;
// 更新数据
dataToSend++;
dataToRecv++;
}
// 关闭 Socket
closesocket(clientSock);
closesocket(serverSock);
// 清理 Winsock 库
WSACleanup();
return 0;
}
```
Client端:
```cpp
#include <iostream>
#include <WinSock2.h>
#pragma comment(lib, "ws2_32.lib")
using namespace std;
int main()
{
// 初始化 Winsock 库
WSADATA wsaData;
WSAStartup(MAKEWORD(2, 2), &wsaData);
// 创建 Socket
SOCKET clientSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
// 连接到服务器
sockaddr_in serverAddr;
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(8888);
serverAddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
connect(clientSock, (sockaddr*)&serverAddr, sizeof(serverAddr));
// 发送和接收数据
int dataToRecv = 0;
int dataToSend = 0;
while (dataToRecv != 19 && dataToSend <= 20) {
// 接收数据
recv(clientSock, (char*)&dataToRecv, sizeof(dataToRecv), 0);
cout << "Client received: " << dataToRecv << endl;
// 更新数据
dataToSend = dataToRecv + 1;
// 发送数据
send(clientSock, (char*)&dataToSend, sizeof(dataToSend), 0);
cout << "Client sent: " << dataToSend << endl;
}
// 关闭 Socket
closesocket(clientSock);
// 清理 Winsock 库
WSACleanup();
return 0;
}
```
这里使用了 Windows 下的 Socket 编程,需要引入 `WinSock2.h` 头文件,并链接 `ws2_32.lib` 库。程序中使用了 `send()` 和 `recv()` 函数发送和接收数据,使用 `closesocket()` 函数关闭 Socket。
阅读全文