C++实现编写程序以SOCKET流式套接字的通信方式,实现客户端和服务器之前的聊天程序完整代码
时间: 2024-10-23 22:11:59 浏览: 44
在C++中,我们可以使用socket编程库来创建一个简单的TCP网络聊天应用程序,这里提供了一个基本的客户端-服务器模型的框架代码示例。注意,为了简洁,这个例子仅包含了关键部分,并未包含完整的异常处理和其他细节。
首先,我们来看服务器端:
```cpp
#include <iostream>
#include <string>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
// Server function
void server(int port) {
int server_socket = socket(AF_INET, SOCK_STREAM, 0);
sockaddr_in server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(port);
server_addr.sin_addr.s_addr = INADDR_ANY;
bind(server_socket, (sockaddr*)&server_addr, sizeof(server_addr));
listen(server_socket, 5);
while (true) {
sockaddr_in client_addr;
socklen_t addr_len = sizeof(client_addr);
int client_socket = accept(server_socket, (sockaddr*)&client_addr, &addr_len);
char buffer[1024] = "";
std::cout << "Accepted connection from: " << inet_ntoa(client_addr.sin_addr) << ":" << ntohs(client_addr.sin_port) << "\n";
// Read and write loop
while (true) {
ssize_t bytes_received = recv(client_socket, buffer, sizeof(buffer), 0);
if (bytes_received <= 0) break; // Break if no more data
std::cout << "Received: " << buffer << "\n";
send(client_socket, buffer, bytes_received, 0); // Echo back to client
}
close(client_socket);
std::cout << "Client disconnected.\n";
}
}
int main() {
int port = 12345; // Choose your desired port
try {
server(port);
} catch (std::exception& e) {
std::cerr << "Error: " << e.what() << '\n';
}
return 0;
}
```
然后是客户端:
```cpp
#include <iostream>
#include <string>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
// Client function
void client(const std::string& hostname, int port) {
int client_socket = socket(AF_INET, SOCK_STREAM, 0);
sockaddr_in server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(port);
inet_pton(AF_INET, hostname.c_str(), &server_addr.sin_addr);
connect(client_socket, (sockaddr*)&server_addr, sizeof(server_addr));
std::string message;
std::getline(std::cin, message);
std::cout << "Sending: " << message << "\n";
send(client_socket, message.c_str(), message.size(), 0);
std::string response;
while (!response.empty()) {
char buffer[1024];
ssize_t bytes_received = recv(client_socket, buffer, sizeof(buffer), 0);
if (bytes_received > 0) response.append(buffer, bytes_received);
}
std::cout << "Received: " << response << "\n";
close(client_socket);
}
int main() {
std::string hostname = "localhost"; // Replace with the server IP or hostname
int port = 12345; // Match the server's port
try {
client(hostname, port);
} catch (std::exception& e) {
std::cerr << "Error: " << e.what() << '\n';
}
return 0;
}
```
阅读全文