socket编程
<将以下的代码段落用
...
包裹起来 -->
sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(12345); // 服务器端口号
sin.sin_addr.s_addr = INADDR_ANY; // 使用本机IP地址
}sAddr;
if (bind(sListen, (struct sockaddr)&sAddr, sizeof(sAddr)) < 0)
{
printf("bind failed. Error %d\n",WSAGetLastError());
return 0;
}
// 开始
if (listen(sListen, 10) < 0)
{
printf("Failed to listen.\n");
return 0;
}
// 接受客户端的连接请求
SOCKET sClient = accept(sListen, NULL, NULL);
if (sClient == INVALID_SOCKET)
{
printf("Failed to accept.\n");
} else {
printf("Accepted a connection.\n");
// ...
} // ...
<将下面的代码段落用
...
包裹起来 -->
```go
include
include "InitSock.h" // Include the Winsock header file
using namespace std;
int main() {
CInitSock initSock; // Initialize the Winsock library
SOCKADDR_IN serverAddr; // Create a server address structure
const char serverIP = "127.0.0.1"; // Server's IP address (replace with the actual server IP)
int serverPort = 12345; // Server's port number (replace with the actual port)
SOCKET clientSocket = INVALID_SOCKET; // Client socket descriptor
const char message = "Hello from the client!"; // Message to send to the server
char receiveBuffer[1024]; // Buffer to receive data from the server
int recvSize; // Size of the received data
int connectResult; // Result of the connect operation
struct timeval timeout; // Structure for setting a timeout on the connect operation (optional)
// ... (Additional code for setting up the timeout, connecting to the server, sending and receiving data, etc.) ...
// Connect to the server using the clientSocket variable and the server's IP and port number. For example:
connectResult = connect(clientSocket, (SOCKADDR)&serverAddr, sizeof(serverAddr));
if (connectResult == SOCKET_ERROR) {
cout << "Failed to connect to the server." << endl;
return -1; // Return an error code or exit the program as needed. You can also use WSAGetLastError() to get more information about the error.
} else {
cout << "Connected to the server successfully." << endl; // Print a success message if the connection is successful. You can now proceed with sending and receiving data from the server. For example: send(clientSocket, message, strlen(message), 0); recv(clientSocket, receiveBuffer, sizeof(receiveBuffer), 0); ... } return 0; } // End of the main function. Remember to close the sockets and clean up any resources used in your program before exiting. For example: closesocket(clientSocket); WSACleanup(); ... } // End of the code snippet. Remember to include all necessary headers and libraries for your program to compile and run successfully. Also, make sure to handle any errors that may occur during the execution of your program. Good luck with your project! ```
代码部分:
定义一个网络地址结构体变量:
sin_family 设置为 AF_INET (地址族,指定地址格式)
u_short类型的 sin_port 用于存储端口号
struct in_addr类型的 sin_addr 用于存储IP地址
char类型的 sin_zero[8] 作为一个空字节数组
创建一个 sockaddr_in 结构体变量 sin,并初始化其成员。
将 sin.sin_family 设置为 AF_INET。
使用 htons 函数设置 sin.sin_port 为 4567(这是一个普通用户可以注册的端口号范围)。
将 sin.sin_addr.S_un.S_addr 设置为 INADDR_ANY,表示绑定到本机的任何IP地址。
调用 bind 函数将套接字 sListen 绑定到本地地址上。
如果绑定失败,则打印错误信息并返回。
调用 listen 函数使套接字进入模式,并设置最大未处理连接数为 2。
如果失败,则打印错误信息并返回。
进入循环,等待并接受客户端的连接请求。
创建一个 sockaddr_in 结构体变量 remoteAddr 用于存储远程地址信息。
定义一个 int 类型的变量 nAddrLen,用于存储 remoteAddr 的长度。
定义一个 SOCKET 类型的变量 sClient,用于存储客户端套接字。
在循环中,调用 accept 函数接受新的连接请求。
如果接受失败,则打印错误信息并继续循环。
如果接受成功,则打印接收到的连接信息,并继续循环。
在主循环中,使用 gets 函数从客户端接收数据,并使用 send 函数向客户端发送数据。
使用 recv 函数从客户端接收数据,并检查接收到的数据长度。
如果接收到的数据长度大于 0,则打印接收到的数据。
关闭与客户端的连接和套接字。
客户端代码部分:
包含必要的头文件和命名空间。
创建并初始化一个 Winsock 库的 CInitSock 对象。
调用 socket 函数创建一个套接字,并设置其为 AF_INET(IPv4)和 SOCK_STREAM(流式套接字)。
如果创建失败,则打印错误信息并退出程序。
填写远程地址信息,包括 sin_family、sin_port 和 sin_addr。
调用 connect 函数连接到服务器。
如果连接失败,则打印错误信息并退出程序。
在主循环中,使用 recv 函数从服务器接收数据,并使用 send 函数向服务器发送数据。
关闭套接字。
封装的InitSock.h内容:
包含必要的头文件,并链接到 WS2_32.lib。
定义 CInitSock 类,用于初始化 Winsock 库。
在类的构造函数中调用 WSAStartup 函数初始化 Winsock 库。
在类的析构函数中调用 WSACleanup 函数清理 Winsock 库资源。