编写程序C++通过TCP协议以流式套接字模式开发一个客户端和服务器端的双向聊天程序的完整代码
时间: 2024-10-27 14:03:21 浏览: 35
在C++中编写一个简单的TCP双向聊天程序涉及到使用`iostream`、`sys/socket.h`、`netinet/in.h`以及`arpa/inet.h`等库。下面是一个简化的示例,展示了客户端和服务器端的基本结构。请注意,这只是一个基础版本,并未包含错误处理和完整的异常处理。
**服务器端(server.cpp):**
```cpp
#include <iostream>
#include <string>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main() {
int server_socket = socket(AF_INET, SOCK_STREAM, 0);
sockaddr_in server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(8000); // 使用默认的localhost IP (127.0.0.1)
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 message[1024];
std::cin.getline(message, sizeof(message));
send(client_socket, message, strlen(message), 0);
recv(client_socket, message, sizeof(message), 0);
std::cout << "Received from client: " << message << std::endl;
close(client_socket);
}
return 0;
}
```
**客户端(client.cpp):**
```cpp
#include <iostream>
#include <string>
#include <cstring>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main() {
int client_socket = socket(AF_INET, SOCK_STREAM, 0);
sockaddr_in server_addr;
server_addr.sin_family = AF_INET;
inet_aton("127.0.0.1", &server_addr.sin_addr);
server_addr.sin_port = htons(8000);
connect(client_socket, (sockaddr*)&server_addr, sizeof(server_addr));
std::string input;
std::getline(std::cin, input);
send(client_socket, input.c_str(), input.length(), 0);
char buffer[1024] = {0};
recv(client_socket, buffer, sizeof(buffer), 0);
std::cout << "Server said: " << buffer << std::endl;
close(client_socket);
return 0;
}
```
运行这个程序时,在终端里分别启动一个服务进程(`./server`)和两个客户端进程(每个客户端连接到不同的实例)。然后,你可以开始在两个客户端之间进行文本交流。
阅读全文