CAsyncSocketEx and Console App
-
Hallo
Ich benutze folgende asynchrone Socket Klasse:
http://www.codeproject.com/KB/IP/casyncsocketex.aspxSie benötigt NICHT die MFC.
Wenn ich sie allerdings doch in MFC Projekten benutze, funktioniert sie natürlich auch problemlos.Jedoch hab ich nun ein einfaches Win32 Console Projekt (ohne MFC) erstellt, und versucht die Socketklasse dort zu benutzen.
Seltsamerweise schaff ich es jedoch nicht, irgend ein Event des Sockets abzufangen, weder Connect noch Receive noch sonst irgendwas.
Auch keine Errors werden angezeigt.Hat jemand ne Idee was ich falsch mache?
Hier noch mein Code:
// MySocket.h #pragma once #include "AsyncSocketEx.h" class CMySocket : public CAsyncSocketEx { public: CMySocket(); virtual void OnConnect(int nErrorCode); virtual void OnReceive(int nErrorCode); virtual ~CMySocket(); };
// MySocket.cpp #include "MySocket.h" #include <iostream> using std::cout; using std::endl; CMySocket::CMySocket() { } CMySocket::~CMySocket() { Close(); } void CMySocket::OnReceive(int nErrorCode) { if (nErrorCode) { cout << "Fatal error! Network subsystem failed!" << endl; Close(); return; } char buffer[4097]; int res=Receive(&buffer, 4096); if (res==SOCKET_ERROR || !res) { if (GetLastError()!=WSAEWOULDBLOCK || !res) { cout << "Error: Connection has been closed." << endl; return; } return; } buffer[res]=0; cout << "Server reply:" << endl << buffer << endl; Close(); } void CMySocket::OnConnect(int nErrorCode) { if (nErrorCode) { cout << "Error: Could not connect to server." << endl; Close(); } else cout << "Status: Connected to server." << endl; }
// main.cpp #include <iostream> #include <string> #include <windows.h> #include "MySocket.h" using namespace std; int CoutAndReturn(std::string strCout, int nReturn=1) { cout << strCout << endl; cout << WSAGetLastError() << endl; return nReturn; } int main() { WSADATA data; if(WSAStartup(MAKEWORD(2, 2), &data) != 0) return CoutAndReturn("Startup failed"); WSAEVENT hEvent = WSA_INVALID_EVENT; hEvent = WSACreateEvent(); if(!hEvent) return CoutAndReturn("Event creation failed"); CMySocket sock; sock.Create(); if(WSAEventSelect(sock.GetSocketHandle(), hEvent, FD_CONNECT|FD_READ) == SOCKET_ERROR) return CoutAndReturn("Selection failed"); if(!sock.Connect("www.spinchat.com", 3001)) return CoutAndReturn("Connect failed"); WaitForSingleObject(hEvent, INFINITE); WSACleanup(); return 0; }
-
Ich frage mich wie du MFC verwenden willst ohne MFC zu verwenden.
-
Unix-Tom schrieb:
Ich frage mich wie du MFC verwenden willst ohne MFC zu verwenden.
Die Sache ist die, dass ich die MFC even NICHT verwenden will.
Ich brauch sie nämlich nicht.
Ich bin jetzt von einer Console auf eine normal Win32 Windows Application umgestiegen, ebenfalls OHNE MFC.
Damit funktioniert die Klasse auch problemlos.
Das Problem war wohl, dass die Console App keine Message Loop hatte.