请用C++winsock2完整地写一个TCP/IP文本传输(指定ip和端口)以实现内网群聊的客户端和服务器的程序
时间: 2024-09-10 18:06:46 浏览: 51
在C++中使用Winsock2库编写一个TCP/IP的文本传输客户端和服务器程序涉及到几个关键步骤。首先,需要包含必要的头文件,并初始化Winsock库。然后定义套接字、连接到服务器或创建服务器监听连接。
**服务器端(Server.cpp):**
```cpp
#include <winsock2.h>
#include <ws2tcpip.h>
#include <iostream>
#include <string>
#pragma comment(lib, "ws2_32.lib")
using namespace std;
int main() {
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
cerr << "Failed to initialize Winsock" << endl;
return 1;
}
int serverPort = 8000; // 端口号
char serverIP[] = "192.168.1.1"; // 内网IP
SOCKET serverSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (serverSocket == INVALID_SOCKET) {
cerr << "Failed to create socket" << endl;
WSACleanup();
return 1;
}
sockaddr_in serverAddress;
serverAddress.sin_family = AF_INET;
serverAddress.sin_port = htons(serverPort);
inet_pton(AF_INET, serverIP, &serverAddress.sin_addr);
bind(serverSocket, (SOCKADDR*)&serverAddress, sizeof(serverAddress));
listen(serverSocket, SOMAXCONN);
cout << "Server started on port " << serverPort << " (" << serverIP << ")" << endl;
while (true) {
SOCKET clientSocket = accept(serverSocket, NULL, NULL);
if (clientSocket == INVALID_SOCKET) {
cerr << "Failed to accept connection" << endl;
continue;
}
char buffer[1024];
recv(clientSocket, buffer, sizeof(buffer), 0);
cout << "Received message from client: " << buffer << endl;
send(clientSocket, "Message received", strlen("Message received"), 0);
closesocket(clientSocket);
}
closesocket(serverSocket);
WSACleanup();
return 0;
}
```
**客户端(Client.cpp):**
```cpp
#include <winsock2.h>
#include <ws2tcpip.h>
#include <iostream>
#include <string>
#pragma comment(lib, "ws2_32.lib")
using namespace std;
int main() {
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
cerr << "Failed to initialize Winsock" << endl;
return 1;
}
string serverIP = "192.168.1.1";
int serverPort = 8000;
SOCKET clientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (clientSocket == INVALID_SOCKET) {
cerr << "Failed to create socket" << endl;
WSACleanup();
return 1;
}
sockaddr_in serverAddress;
serverAddress.sin_family = AF_INET;
serverAddress.sin_port = htons(serverPort);
inet_pton(AF_INET, serverIP.c_str(), &serverAddress.sin_addr);
connect(clientSocket, (SOCKADDR*)&serverAddress, sizeof(serverAddress));
cout << "Connecting to server at " << serverIP << ":" << serverPort << endl;
send(clientSocket, "Hello, Server!", strlen("Hello, Server!"), 0);
char buffer[1024];
recv(clientSocket, buffer, sizeof(buffer), 0);
cout << "Received message from server: " << buffer << endl;
WSACleanup();
closesocket(clientSocket);
return 0;
}
```
**注意事项:**
1. 这些代码假设您已经在本地网络环境中配置了防火墙规则并允许通信。
2. `WSACleanup`函数应在每次成功完成操作后尽早调用,以释放资源。
3. 实际应用中可能需要处理更多的错误情况和异常。
阅读全文