我正在尝试学习Winsock,当我尝试运行此代码时:
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#include <iostream>
#include <WS2tcpip.h>
#include <thread>
#include <chrono>
#pragma comment(lib, "ws2_32.lib")
using namespace std;
void main() {
// Initialize Winsock
WSAData data;
WORD ver = MAKEWORD(2, 2);
int wsOk = WSAStartup(ver, &data);
if (wsOk != 0) { cerr << "Can't start winsock! Tactical Retreat!" << endl;
return;
}
// Create socket
SOCKET listening = socket(AF_INET, SOCK_STREAM, 0);
if (listening == INVALID_SOCKET) {
cerr << "Couldn't create socket!" << endl;
return;
}
// Bind the ip address and port to a socket
sockaddr_in hint; hint.sin_family = AF_INET;
hint.sin_port = htons(3800);
hint.sin_addr.S_un.S_addr = INADDR_ANY; // or inet_pton
bind(listening, (sockaddr*)&hint, sizeof(hint));
//Tell winsock the socket is for listening
listen(listening, SOMAXCONN); // Wait for a connection
sockaddr_in client;
int clientSize = sizeof(client);
SOCKET clientSocket = accept(listening, (sockaddr*) &client, &clientSize);
char host[NI_MAXHOST]; // Client's remote name
char service[NI_MAXHOST]; // Service (i.e port)
ZeroMemory(host, NI_MAXHOST); ZeroMemory(service, NI_MAXHOST);
if (getnameinfo((sockaddr*)&client, sizeof(client), host, NI_MAXHOST, service, NI_MAXSERV, 0) == 0) {
cout << " connected on port " << service << endl; }
else { inet_ntop(AF_INET, &client.sin_addr, host, NI_MAXHOST);
cout << host << " connected on port" << htons(client.sin_port) << endl; } // Close listening socket closesocket(listening); // While loop: accept and echo message back to client
char buf[4096];
while (true) {
ZeroMemory(buf, 4096); // Wait for client to send data
int bytesRecieved = recv(clientSocket, buf, 4096, 0);
if (bytesRecieved == SOCKET_ERROR) {
cerr << "Error in recv(). Quitting" << endl;
break;
}
if (bytesRecieved == 0) {
cout << "client disconnected " << endl;
break;
} // Echo message back to client
send(clientSocket, buf, bytesRecieved * 1, 0);
}// Close
closesocket(clientSocket); // Cleanup Winsock
WSACleanup();
std::this_thread::sleep_for(std::chrono::milliseconds(10000));
}
这是从我复制并试图自己运行的youtube教程中获取的代码。每次我运行它,它说客户端已连接IP地址:204.204.204.204。我已经解决了问题,但我仍然无法让它工作......似乎问题来自:
sockaddr_in client;
int clientSize = sizeof(client);
SOCKET clientSocket = accept(listening, (sockaddr*) &client, &clientSize);
我不确定为什么它已经接受了连接。我没有看到任何错误。
编辑:
我做了一个接受检查但它失败了:
if (clientSocket == INVALID_SOCKET) {
cout << "error on socket" << endl;
std::this_thread::sleep_for(std::chrono::milliseconds(10000));
return;
}
似乎&clientSize
检索NULL
。我不知道该怎么做。