编写一段C++示例代码,一个程序往另外一个程序发送数据包,使用TCP通信协议
时间: 2024-04-10 14:26:57 浏览: 89
C++实现的TCP协议的文件传输
3星 · 编辑精心推荐
以下是使用TCP通信协议,在C++中编写的示例代码,其中一个程序作为发送方,另一个程序作为接收方:
发送方程序(client.cpp):
```cpp
#include <iostream>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
int main() {
int clientSocket = socket(AF_INET, SOCK_STREAM, 0);
// 目标主机和端口
struct sockaddr_in serverAddress;
serverAddress.sin_family = AF_INET;
serverAddress.sin_port = htons(12345);
serverAddress.sin_addr.s_addr = inet_addr("127.0.0.1");
// 连接到服务器
if (connect(clientSocket, (struct sockaddr*)&serverAddress, sizeof(serverAddress)) == -1) {
std::cerr << "连接失败" << std::endl;
return 1;
}
// 准备要发送的数据
const char* data = "Hello, server!";
// 发送数据
if (send(clientSocket, data, strlen(data), 0) == -1) {
std::cerr << "发送失败" << std::endl;
close(clientSocket);
return 1;
}
// 关闭套接字
close(clientSocket);
return 0;
}
```
接收方程序(server.cpp):
```cpp
#include <iostream>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
int main() {
int serverSocket = socket(AF_INET, SOCK_STREAM, 0);
// 绑定地址和端口
struct sockaddr_in serverAddress;
serverAddress.sin_family = AF_INET;
serverAddress.sin_port = htons(12345);
serverAddress.sin_addr.s_addr = INADDR_ANY;
if (bind(serverSocket, (struct sockaddr*)&serverAddress, sizeof(serverAddress)) == -1) {
std::cerr << "绑定失败" << std::endl;
return 1;
}
// 监听连接
if (listen(serverSocket, 1) == -1) {
std::cerr << "监听失败" << std::endl;
return 1;
}
std::cout << "等待客户端连接..." << std::endl;
// 接受客户端连接
struct sockaddr_in clientAddress;
socklen_t clientAddressSize = sizeof(clientAddress);
int clientSocket = accept(serverSocket, (struct sockaddr*)&clientAddress, &clientAddressSize);
std::cout << "客户端已连接" << std::endl;
// 接收数据
char buffer[1024];
ssize_t bytesRead = recv(clientSocket, buffer, sizeof(buffer), 0);
if (bytesRead == -1) {
std::cerr << "接收失败" << std::endl;
close(clientSocket);
close(serverSocket);
return 1;
}
// 打印接收到的数据
std::cout << "接收到的数据: " << buffer << std::endl;
// 关闭套接字
close(clientSocket);
close(serverSocket);
return 0;
}
```
您可以将上述代码分别保存为client.cpp和server.cpp,并使用C++编译器编译两个程序。发送方程序将向接收方程序发送数据包,并在接收方程序中打印接收到的数据。
请注意将IP地址和端口号配置为适合您的实际情况。在示例中,使用的是本地回环地址127.0.0.1和端口号12345。
阅读全文