有通过C++实现的代码么
时间: 2024-02-18 18:59:10 浏览: 68
通用的C++数据结构代码实现,可直接运行调试,使用模板
以下是使用C++实现字符大小写转换的示例代码(使用TCP套接字):
服务端代码:
```cpp
#include <iostream>
#include <cstring>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#define PORT 8888
int main()
{
int server_socket = socket(AF_INET, SOCK_STREAM, 0);
if (server_socket == -1)
{
std::cerr << "Failed to create socket\n";
return -1;
}
sockaddr_in server_address{};
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = INADDR_ANY;
server_address.sin_port = htons(PORT);
if (bind(server_socket, (sockaddr*)&server_address, sizeof(server_address)) == -1)
{
std::cerr << "Failed to bind socket\n";
return -1;
}
if (listen(server_socket, 1) == -1)
{
std::cerr << "Failed to listen socket\n";
return -1;
}
std::cout << "Server listening on port " << PORT << "...\n";
sockaddr_in client_address{};
socklen_t client_address_length = sizeof(client_address);
while (true)
{
int client_socket = accept(server_socket, (sockaddr*)&client_address, &client_address_length);
if (client_socket == -1)
{
std::cerr << "Failed to accept connection\n";
continue;
}
std::cout << "Connected by " << inet_ntoa(client_address.sin_addr) << "\n";
while (true)
{
char buffer[1024]{};
int bytes_received = recv(client_socket, buffer, sizeof(buffer), 0);
if (bytes_received <= 0)
{
break;
}
std::string data(buffer, bytes_received);
if (std::all_of(data.begin(), data.end(), isalpha))
{
std::transform(data.begin(), data.end(), data.begin(), [](unsigned char c) { return std::islower(c) ? std::toupper(c) : std::tolower(c); });
send(client_socket, data.c_str(), data.length(), 0);
}
}
close(client_socket);
}
close(server_socket);
return 0;
}
```
客户端代码:
```cpp
#include <iostream>
#include <cstring>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#define PORT 8888
int main()
{
int client_socket = socket(AF_INET, SOCK_STREAM, 0);
if (client_socket == -1)
{
std::cerr << "Failed to create socket\n";
return -1;
}
sockaddr_in server_address{};
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = inet_addr("127.0.0.1");
server_address.sin_port = htons(PORT);
if (connect(client_socket, (sockaddr*)&server_address, sizeof(server_address)) == -1)
{
std::cerr << "Failed to connect to server\n";
return -1;
}
while (true)
{
std::string data;
std::cout << "Enter string to convert: ";
std::getline(std::cin, data);
if (data.empty())
{
break;
}
send(client_socket, data.c_str(), data.length(), 0);
char buffer[1024]{};
int bytes_received = recv(client_socket, buffer, sizeof(buffer), 0);
if (bytes_received <= 0)
{
break;
}
std::cout << "Converted string: " << buffer << "\n";
}
close(client_socket);
return 0;
}
```
服务端启动后,可以运行客户端并输入要转换的字符串,客户端会将其发送到服务端进行转换并输出结果。
阅读全文