IPC C++ Python



  • Hallo,

    ich will eine PythonAPI für ein C++ Programm an dem ich zur Zeit arbeite zur Verfügung stellen. Dazu möchte ich Sockets benutzen. Eigentlich funktioniert auch alles, ich bekomme eine Verbindung mit dem Server, der Server bekommt aber leider nur leere Daten gesendet. Der recv Befehl wird angesprungen und er bekommt auch etwas, allerdings ist das Ergebnis immer 0. (In der anderen Richtung macht es auch Probleme, ich kann auch einen manuell gefüllten Buffer nicht wieder zurück schicken). Ich komm nicht drauf was ich falsch mache und wäre deshalb für jede Hilfe dankbar.

    Gruß

    Toby

    Der Server:

    APIController::APIController(const char* _port)
    {
    	port = _port;
    	round = 0;
    	this->init();
    }
    
    APIController::~APIController(void)
    {
    	// shutdown the connection since we're done
        iResult = shutdown(ClientSocket, SD_SEND);
        if (iResult == SOCKET_ERROR) 
    	{
            printf("shutdown failed: %d\n", WSAGetLastError());
            closesocket(ClientSocket);
            WSACleanup();
        }
    
        // cleanup
        closesocket(ClientSocket);
        WSACleanup();
    }
    
    void APIController::init()
    {
    	printf("Round: %d\n", round);
    	// Initialize Winsock
        iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
        if (iResult != 0) 
    	{
            printf("WSAStartup failed: %d\n", iResult);
        }
    	printf("WSAStartup OK\n");
    
    	ZeroMemory(&hints, sizeof(hints));
        hints.ai_family = AF_INET;
        hints.ai_socktype = SOCK_STREAM;
        hints.ai_protocol = IPPROTO_TCP;
        hints.ai_flags = AI_PASSIVE;
    
    	// Resolve the server address and port
        iResult = getaddrinfo(NULL, port, &hints, &result);
        if ( iResult != 0 ) 
    	{
            printf("getaddrinfo failed: %d\n", iResult);
            WSACleanup();
        }
    	printf("getaddrinfo OK\n");
    
        // Create a SOCKET for connecting to server
        ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
        if (ListenSocket == INVALID_SOCKET) 
    	{
            printf("socket failed: %ld\n", WSAGetLastError());
            freeaddrinfo(result);
            WSACleanup();
        }
    	printf("socket OK\n");
    
        // Setup the TCP listening socket
        iResult = bind( ListenSocket, result->ai_addr, (int)result->ai_addrlen);
        if (iResult == SOCKET_ERROR) 
    	{
            printf("bind failed: %d\n", WSAGetLastError());
            freeaddrinfo(result);
            closesocket(ListenSocket);
            WSACleanup();
        }
    	printf("bind OK\n");
    
        freeaddrinfo(result);
    	round++;
    }
    
    int APIController::receiveData(char* &recvdata)
    {
    	iResult = listen(ListenSocket, SOMAXCONN);
        if (iResult == SOCKET_ERROR) 
    	{
            printf("listen failed: %d\n", WSAGetLastError());
            closesocket(ListenSocket);
            WSACleanup();
        }
    	printf("listening for connection...\n");
    
        // Accept a client socket
        ClientSocket = accept(ListenSocket, NULL, NULL);
        if (ClientSocket == INVALID_SOCKET) 
    	{
            printf("accept failed: %d\n", WSAGetLastError());
            closesocket(ListenSocket);
            WSACleanup();
        }
    	printf("connection accepted\n");
    
        // No longer need server socket
        closesocket(ListenSocket);
    
    	// Receive until the peer shuts down the connection
        do 
    	{
            iResult = recv(ClientSocket, recvbuf, recvbuflen, 0);
    
    		if (iResult > 0) 
    		{
                printf("Bytes received: %d\n", iResult);
    
    			// Echo the buffer back to the sender
                iSendResult = send( ClientSocket, recvbuf, iResult, 0 );
                if (iSendResult == SOCKET_ERROR) 
    			{
                    printf("send failed: %d\n", WSAGetLastError());
                    closesocket(ClientSocket);
                    WSACleanup();
                    return 10;
                }
                printf("Bytes sent: %d\n", iSendResult);
            }
            else if (iResult == 0)
                printf("No bytes recieved...\n");
            else  
    		{
                printf("recv failed: %d\n", WSAGetLastError());
                closesocket(ClientSocket);
                WSACleanup();
                return 11;
            }
        } 
    	while (iResult > 0);
    
    	closesocket(ClientSocket);
    
    	return 12;
    }
    

    Der Client

    import asyncore, socket
    
    class SocketHandler(asyncore.dispatcher):
    
        def __init__(self, host, port):
            asyncore.dispatcher.__init__(self)
            self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
            self.connect( (host, port) )
            self.buffer = bytes('Hallo from python', 'ascii')
    
        def handle_connect(self):
            pass
    
        def handle_close(self):
            self.close()
    
        def handle_read(self):
            print(self.recv(8192))
    
        def writable(self):
            return (len(self.buffer) > 0)
    
        def handle_write(self):
            totalsent = 0
            while totalsent < len(self.buffer):
                sent = self.sock.send(self.buffer[totalsent:])
                if sent == 0:
                    raise RuntimeError("socket connection broken")
                totalsent = totalsent + sent
    
            self.buffer = self.buffer[sent:]
    
    if __name__ == '__main__':
    
        sock = SocketHandler("127.0.0.1", 27015)
        asyncore.loop()
    

Anmelden zum Antworten