socket server funktioniert als konsolenanwendung, aber nicht als dll



  • hallo,

    habe folgende konsolenanwendung programmiert :

    /* 	Rot13 server example
     *  View with tabsize = 4
     *	Part of the Winsock networking tutorial by Thomas Bleeker
     *	Visit www.MadWizard.org
     */
    #include "stdafx.h"
    #include <iostream>
    #include <string>
    #include <sstream>
    
    #define WIN32_MEAN_AND_LEAN
    #include <winsock2.h>
    #include <windows.h>
    
    using namespace std;
    
    class ROTException
    {
    public:
        ROTException() :
             m_pMessage("") {}
        virtual ~ROTException() {}
        ROTException(const char *pMessage) :
             m_pMessage(pMessage) {}
        const char * what() { return m_pMessage; }
    private:
        const char *m_pMessage;
    };
    
    const int  REQ_WINSOCK_VER   = 2;	// Minimum winsock version required
    const int  DEFAULT_PORT      = 4444;	
    const int  TEMP_BUFFER_SIZE  = 128;
    
    string GetHostDescription(const sockaddr_in &sockAddr)
    {
    	ostringstream stream;
    	stream << inet_ntoa(sockAddr.sin_addr) << ":" << ntohs(sockAddr.sin_port);
    	return stream.str();
    }
    
    void SetServerSockAddr(sockaddr_in *pSockAddr, int portNumber)
    {
    	// Set family, port and find IP
    	pSockAddr->sin_family = AF_INET;
    	pSockAddr->sin_port = htons(portNumber);
    	pSockAddr->sin_addr.S_un.S_addr = INADDR_ANY;
    }
    
    void rot13(char *pBuffer, int size)
    {
    	for(int i=0;i<size;i++)
    	{
    		char c = pBuffer[i];
    		if ((c >= 'a' && c < 'n') || (c >= 'A' && c < 'N') )
    			c += 13;
    		else if ((c>='n' && c <= 'z') || (c>='N' && c <= 'Z'))
    			c -= 13;
    		else
    			continue;
    		pBuffer[i] = c;
    	}
    }
    
    void HandleConnection(SOCKET hClientSocket, const sockaddr_in &sockAddr)
    {
    	// Print description (IP:port) of connected client
    	cout << "Connected with " << GetHostDescription(sockAddr) << ".\n";
    
    	char tempBuffer[TEMP_BUFFER_SIZE];
    
    	// Read data
    	while(true)
    	{
    		int retval;
    		retval = recv(hClientSocket, tempBuffer, sizeof(tempBuffer), 0);
    		if (retval==0)
    		{ 
    			break; // Connection has been closed
    		}
    		else if (retval==SOCKET_ERROR)
    		{
    			throw ROTException("socket error while receiving.");
    		}
    		else
    		{
    			// retval is the number of bytes received.
    			  // rot13 the data and send it back to the client */
    			for(int i=0;i<retval;i++)
    		{
    			cout << tempBuffer[i];
    
    			}
    			/*rot13(tempBuffer, retval);
    
    			System::Byte aBytes[];
    
    			String *sString = System::Text::Encoding::ASCII->GetString(aBytes);
    
    			cout << rot13;*/
    
    			//if (send(hClientSocket, tempBuffer, retval, 0)==SOCKET_ERROR)
    				//throw ROTException("socket error while sending.");
    		}
    	}
    	cout << "Connection closed.\n";
    }
    
    bool RunServer(int portNumber)
    {
    	SOCKET 		hSocket = INVALID_SOCKET,
    				hClientSocket = INVALID_SOCKET;
    	bool		bSuccess = true;
    	sockaddr_in	sockAddr = {0};
    
    	try
    	{
    		// Create socket
    		cout << "Creating socket... ";
    		if ((hSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET)
    			throw ROTException("could not create socket.");
    		cout << "created.\n";
    
    		// Bind socket
    		cout << "Binding socket... ";
    		SetServerSockAddr(&sockAddr, portNumber);
    		if (bind(hSocket, reinterpret_cast<sockaddr*>(&sockAddr), sizeof(sockAddr))!=0)
    			throw ROTException("could not bind socket.");
    		cout << "bound.\n";
    
    		// Put socket in listening mode
    		cout << "Putting socket in listening mode... ";
    		if (listen(hSocket, SOMAXCONN)!=0)
    			throw ROTException("could not put socket in listening mode.");
    		cout << "done.\n";
    
    		// Wait for connection
    		cout << "Waiting for incoming connection... ";
    
    		sockaddr_in clientSockAddr;
    		int			clientSockSize = sizeof(clientSockAddr);
    
    		// Accept connection:
    		hClientSocket = accept(hSocket,
    						 reinterpret_cast<sockaddr*>(&clientSockAddr),
    						 &clientSockSize);
    
    		// Check if accept succeeded
    		if (hClientSocket==INVALID_SOCKET)
    			throw ROTException("accept function failed.");
    		cout << "accepted.\n";
    
    		// Wait for and accept a connection:
    		HandleConnection(hClientSocket, clientSockAddr);
    
    	}
    	catch(ROTException e)
    	{
    		cerr << "\nError: " << e.what() << endl;
    		bSuccess = false; 
    	}
    
    	if (hSocket!=INVALID_SOCKET)
    		closesocket(hSocket);
    
    	if (hClientSocket!=INVALID_SOCKET)
    		closesocket(hClientSocket);
    
    	return bSuccess;
    }	
    
    int main(int argc, char* argv[])
    { 
    	int iRet = 1;
    	WSADATA wsaData;
    
    	cout << "Initializing winsock... ";
    
    	if (WSAStartup(MAKEWORD(REQ_WINSOCK_VER,0), &wsaData)==0)
    	{
    		// Check if major version is at least REQ_WINSOCK_VER
    		if (LOBYTE(wsaData.wVersion) >= REQ_WINSOCK_VER)
    		{
    			cout << "initialized.\n";
    
    			int port = DEFAULT_PORT;
    			if (argc > 1)
    				port = atoi(argv[1]);
    			iRet = !RunServer(port);
    		}
    		else
    		{
    			cerr << "required version not supported!";
    		}
    
    		cout << "Cleaning up winsock... ";
    
    		// Cleanup winsock
    		if (WSACleanup()!=0)
    		{
    			cerr << "cleanup failed!\n";
    			iRet = 1;
    		}   
    		cout << "done.\n";
    	}
    	else
    	{
    		cerr << "startup failed!\n";
    	}
    	return iRet;
    }
    

    aber die dll version davon wo der empfangene string an die export funktion weitergegeben werden soll, klappt nicht :

    // dllsocket.cpp : Definiert die exportierten Funktionen für die DLL-Anwendung.
    //
    
    #include "stdafx.h"
    #include "dllsocket.h"
    #include <sstream>
    #include <windows.h>
    #include <winsock2.h>
    #include <iostream>
    #include <string>
    
    #define WIN32_MEAN_AND_LEAN
    using namespace std;
    
    static char* str;
    
    class ROTException
    {
    public:
        ROTException() :
             m_pMessage("") {}
        virtual ~ROTException() {}
        ROTException(const char *pMessage) :
             m_pMessage(pMessage) {}
        const char * what() { return m_pMessage; }
    private:
        const char *m_pMessage;
    };
    
    const int  REQ_WINSOCK_VER   = 2;	// Minimum winsock version required
    const int  DEFAULT_PORT      = 4444;	
    const int  TEMP_BUFFER_SIZE  = 128;
    
    string GetHostDescription(const sockaddr_in &sockAddr)
    {
    	ostringstream stream;
    	stream << inet_ntoa(sockAddr.sin_addr) << ":" << ntohs(sockAddr.sin_port);
    	return stream.str();
    }
    
    void SetServerSockAddr(sockaddr_in *pSockAddr, int portNumber)
    {
    	// Set family, port and find IP
    	pSockAddr->sin_family = AF_INET;
    	pSockAddr->sin_port = htons(portNumber);
    	pSockAddr->sin_addr.S_un.S_addr = INADDR_ANY;
    }
    
    void HandleConnection(SOCKET hClientSocket, const sockaddr_in &sockAddr)
    {
    	// Print description (IP:port) of connected client
    	cout << "Connected with " << GetHostDescription(sockAddr) << ".\n";
    
    	char tempBuffer[TEMP_BUFFER_SIZE];
    
    	// Read data
    	while(true)
    	{
    		int retval;
    		retval = recv(hClientSocket, tempBuffer, sizeof(tempBuffer), 0);
    		if (retval==0)
    		{ 
    			break; // Connection has been closed
    		}
    		else if (retval==SOCKET_ERROR)
    		{
    			throw ROTException("socket error while receiving.");
    		}
    		else
    		{
    			// retval is the number of bytes received.
    			  // rot13 the data and send it back to the client */
    			str="";
    			for(int i=0;i<retval;i++)
    			{
    			str=str+tempBuffer[i];
    			}
    			/*rot13(tempBuffer, retval);
    
    			System::Byte aBytes[];
    
    			String *sString = System::Text::Encoding::ASCII->GetString(aBytes);
    
    			cout << rot13;*/
    
    			//if (send(hClientSocket, tempBuffer, retval, 0)==SOCKET_ERROR)
    				//throw ROTException("socket error while sending.");
    		}
    	}
    	cout << "Connection closed.\n";
    }
    
    bool RunServer(int portNumber)
    {
    	SOCKET 		hSocket = INVALID_SOCKET,
    				hClientSocket = INVALID_SOCKET;
    	bool		bSuccess = true;
    	sockaddr_in	sockAddr = {0};
    
    	try
    	{
    		// Create socket
    		cout << "Creating socket... ";
    		if ((hSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET)
    			throw ROTException("could not create socket.");
    		cout << "created.\n";
    
    		// Bind socket
    		cout << "Binding socket... ";
    		SetServerSockAddr(&sockAddr, portNumber);
    		if (bind(hSocket, reinterpret_cast<sockaddr*>(&sockAddr), sizeof(sockAddr))!=0)
    			throw ROTException("could not bind socket.");
    		cout << "bound.\n";
    
    		// Put socket in listening mode
    		cout << "Putting socket in listening mode... ";
    		if (listen(hSocket, SOMAXCONN)!=0)
    			throw ROTException("could not put socket in listening mode.");
    		cout << "done.\n";
    
    		// Wait for connection
    		cout << "Waiting for incoming connection... ";
    
    		sockaddr_in clientSockAddr;
    		int			clientSockSize = sizeof(clientSockAddr);
    
    		// Accept connection:
    		hClientSocket = accept(hSocket,
    						 reinterpret_cast<sockaddr*>(&clientSockAddr),
    						 &clientSockSize);
    
    		// Check if accept succeeded
    		if (hClientSocket==INVALID_SOCKET)
    			throw ROTException("accept function failed.");
    		cout << "accepted.\n";
    
    		// Wait for and accept a connection:
    		HandleConnection(hClientSocket, clientSockAddr);
    
    	}
    	catch(ROTException e)
    	{
    		cerr << "\nError: " << e.what() << endl;
    		bSuccess = false; 
    	}
    
    	if (hSocket!=INVALID_SOCKET)
    		closesocket(hSocket);
    
    	if (hClientSocket!=INVALID_SOCKET)
    		closesocket(hClientSocket);
    
    	return bSuccess;
    }	
    
    // Dies ist das Beispiel einer exportierten Variable.
    DLLSOCKET_API int ndllsocket=0;
    
    // Dies ist das Beispiel einer exportierten Funktion.
    DLLSOCKET_API char* fndllsocket(void)
    {
    	int iRet = 1;
    	WSADATA wsaData;
    
    	cout << "Initializing winsock... ";
    
    	if (WSAStartup(MAKEWORD(REQ_WINSOCK_VER,0), &wsaData)==0)
    	{
    		// Check if major version is at least REQ_WINSOCK_VER
    		if (LOBYTE(wsaData.wVersion) >= REQ_WINSOCK_VER)
    		{
    			cout << "initialized.\n";
    
    			int port = DEFAULT_PORT;
    
    			iRet = !RunServer(port);
    		}
    		else
    		{
    			cerr << "required version not supported!";
    		}
    
    		cout << "Cleaning up winsock... ";
    
    		// Cleanup winsock
    		 //int Desinfektionsloesung::berechneKonzentratanteil()
    		if (WSACleanup()!=0)
    		{
    			cerr << "cleanup failed!\n";
    			iRet = 1;
    		}   
    		cout << "done.\n";
    	}
    	else
    	{
    		cerr << "startup failed!\n";
    	}
    	return str;
    }
    
    // Dies ist der Konstruktor einer Klasse, die exportiert wurde.
    // Siehe dllsocket.h für die Klassendefinition.
    Cdllsocket::Cdllsocket()
    {
    	return;
    }
    

    ich bekomme folgende fehlermeldung :

    1>------ Erstellen gestartet: Projekt: dllsocket, Konfiguration: Debug Win32 ------
    1>  dllsocket.cpp
    1>     Bibliothek "c:\users\user\documents\visual studio 2010\Projects\dllsocket\Debug\dllsocket.lib" und Objekt "c:\users\user\documents\visual studio 2010\Projects\dllsocket\Debug\dllsocket.exp" werden erstellt.
    1>dllsocket.obj : error LNK2019: Verweis auf nicht aufgelöstes externes Symbol "__imp__inet_ntoa@4" in Funktion ""class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __cdecl GetHostDescription(struct sockaddr_in const &)" (?GetHostDescription@@YA?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@ABUsockaddr_in@@@Z)".
    1>dllsocket.obj : error LNK2019: Verweis auf nicht aufgelöstes externes Symbol "__imp__ntohs@4" in Funktion ""class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __cdecl GetHostDescription(struct sockaddr_in const &)" (?GetHostDescription@@YA?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@ABUsockaddr_in@@@Z)".
    1>dllsocket.obj : error LNK2019: Verweis auf nicht aufgelöstes externes Symbol "__imp__htons@4" in Funktion ""void __cdecl SetServerSockAddr(struct sockaddr_in *,int)" (?SetServerSockAddr@@YAXPAUsockaddr_in@@H@Z)".
    1>dllsocket.obj : error LNK2019: Verweis auf nicht aufgelöstes externes Symbol "__imp__recv@16" in Funktion ""void __cdecl HandleConnection(unsigned int,struct sockaddr_in const &)" (?HandleConnection@@YAXIABUsockaddr_in@@@Z)".
    1>dllsocket.obj : error LNK2019: Verweis auf nicht aufgelöstes externes Symbol "__imp__closesocket@4" in Funktion "__catch$?RunServer@@YA_NH@Z$0".
    1>dllsocket.obj : error LNK2019: Verweis auf nicht aufgelöstes externes Symbol "__imp__accept@12" in Funktion ""bool __cdecl RunServer(int)" (?RunServer@@YA_NH@Z)".
    1>dllsocket.obj : error LNK2019: Verweis auf nicht aufgelöstes externes Symbol "__imp__listen@8" in Funktion ""bool __cdecl RunServer(int)" (?RunServer@@YA_NH@Z)".
    1>dllsocket.obj : error LNK2019: Verweis auf nicht aufgelöstes externes Symbol "__imp__bind@12" in Funktion ""bool __cdecl RunServer(int)" (?RunServer@@YA_NH@Z)".
    1>dllsocket.obj : error LNK2019: Verweis auf nicht aufgelöstes externes Symbol "__imp__socket@12" in Funktion ""bool __cdecl RunServer(int)" (?RunServer@@YA_NH@Z)".
    1>dllsocket.obj : error LNK2019: Verweis auf nicht aufgelöstes externes Symbol "__imp__WSACleanup@0" in Funktion ""char * __cdecl fndllsocket(void)" (?fndllsocket@@YAPADXZ)".
    1>dllsocket.obj : error LNK2019: Verweis auf nicht aufgelöstes externes Symbol "__imp__WSAStartup@8" in Funktion ""char * __cdecl fndllsocket(void)" (?fndllsocket@@YAPADXZ)".
    1>c:\users\user\documents\visual studio 2010\Projects\dllsocket\Debug\dllsocket.dll : fatal error LNK1120: 11 nicht aufgelöste externe Verweise.
    ========== Erstellen: 0 erfolgreich, Fehler bei 1, 0 aktuell, 0 übersprungen ==========
    


  • Das sieht so aus, als ob Du die ws2_32.lib nicht mitlinken würdest.



  • hab ich gemacht, danke für die hilfe,

    jetzt habe ich ein neues problem, is glaube ich relativ simpel ...

    habe ein char array tempBuffer

    und das soll in char* __stdcall umgewandelt werden,

    immer wenn ich die dll aufrufe bekomme ich die meldung

    clared with a different calling convention

    sowas wie

    char* __stdcall st;

    st=st+tempbuffer[0] und dann für tempbuffer[1] inner schleife

    klappt nicht ...



  • also in java sage ich folgendes :

    String df="dssffffffffffffffffffffffffffdsd";
    byte[] theByteArray = df.getBytes();
    output.write(theByteArray);

    heraus kommt :

    100
    115
    115
    102
    102
    102
    102
    102
    102
    102
    102
    102
    102
    102
    102
    102
    102
    102
    102
    102
    102
    102
    102
    102
    102
    102
    102
    102
    102
    100
    115
    100

    so das sind die ascii werte nehme ich an

    und dies soll in der c++ dll wieder in einen string umgewandelt werden

    und zwar in diese format :

    wenn bei der c++ dll es einen tempBuffer char array gibt

    char* __stdcall
    

    wie geht das?

    ich bekomme ständig error das entweder code nicht lesbar programm stürzt ab und so weiter

    wenn ich einen einfachen testtring nehme :

    char* __stdcall test= "test";

    klappt es aber std::string führt zum absturz des programms welches die dll-funktion aufurft


Anmelden zum Antworten