我正在尝试为 python 服务器创建 C++ 套接字客户端。因为在创建 C++ 客户端之前我是 C++ 新手,所以我检查了 python 套接字服务器是否带有 python 客户端。创建并运行 C++ 客户端后,服务器没有任何连接
服务器.py
def start_listener():
ip = "0.0.0.0"
port = 4444
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
# Tying to bind
server.bind((ip, port))
server.listen(3)
print("[+] Server bind on %s:%d" %(ip,port))
except socket.error as error:
print("[!] Unable to bind on %s:%d" %(ip,port))
# Waiting for connections and handle them
while True:
print("Wating for connections...")
# Waiting part
connenction, addr = server.accept()
print("[+] Accecpted connection from %s:%d" % (addr[0],addr[1]))
data = connenction.recv(2000).decode()
print(data)
start_listener()
ClientSocket.cpp:
#include "ClientSocket.h"
#include <iostream>
ClientSocket::ClientSocket(string ip, int port) {
socket_ip = ip;
socket_port = port;
}
void ClientSocket::CreateSession(){
ClientSocket::sock = socket(AF_INET, SOCK_STREAM, 0);
if(ClientSocket::sock < 0){
cout << "[!] Unable to create socket" << endl;
}
struct sockaddr_in serv_addr;
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = inet_addr((ClientSocket::socket_ip).c_str());
serv_addr.sin_port = htons(ClientSocket::socket_port);
if(connect(ClientSocket::sock, (SOCKADDR *)&serv_addr ,sizeof(sockaddr)) < 0){
cout << "[!] Unable to connect to remote socket" << endl;
}
}
客户端套接字.h
#include <string>
#include <list>
#include <winsock2.h>
#include <Ws2tcpip.h>
using namespace std;
#ifndef SOCKET_H
#define SOCKET_H
class ClientSocket {
private:
string socket_ip;
int socket_port;
SOCKET sock;
public:
ClientSocket(string ip, int port);
void PrintSocket();
void CreateSession();
void SendData(string data);
};
#endif // SOCKET_H
主文件
#include "ClientSocket.h"
using namespace std;
int main() {
ClientSocket clientsocket ("127.0.0.1", 4444);
clientsocket.CreateSession();
return 0;
}
输出
[!] Unable to connect to remote socket
包含<errno.h>
并打印错误后,它的打印没有错误