Event and/or socket problems

Jonas Bengtsson jonas.b at gmail.com
Wed Jan 23 18:52:20 PST 2008


Hi all,

I'm trying to get to grips with sockets in wxwidgets. I have a few problems:

1) I don't get any events on incoming data or lost connection. I think 
I've set up everything as I should. The main thing that differs between 
my test application and the Socket sample seem to be that I don't have a 
wxWindow/wxFrame but instead create my own class that derives from 
wxEvtHandler. Perhaps I haven't set up the event handler correctly? Do I 
need to hook it up to something (besides the socket->SetEventHandler() 
call)?

2) My other problem is that if the server isn't running (i.e. I can't 
connect at the beginning) I can't connect when the server is started 
(I'm doing a while(!socket->WaitOnConnect(1)) loop).

Any ideas?

I've attached my test app, which should be self explanatory.

TIA,

Jonas

------------------------------------------------------------

#include <wx/app.h>
#include <wx/socket.h>
#include <iostream>

using std::endl;
using std::cout;

class App : public wxApp
{
public:
	bool OnInit();
};

class SocketClient : public wxEvtHandler
{
public:
	SocketClient(const wxString& host, unsigned int port);
	~SocketClient();
private:
	void OnSocketEvent(wxSocketEvent& event);
private:
	wxSocketClient* m_client;
	DECLARE_EVENT_TABLE()
};

////////////////////////////////////////////////////////////
// class App
////////////////////////////////////////////////////////////


IMPLEMENT_APP(App)

bool App::OnInit()
{
	SocketClient* client = new SocketClient(_("localhost"), 3000);
}

////////////////////////////////////////////////////////////
// class SocketClient
////////////////////////////////////////////////////////////

enum EventTypes
{
	SOCKET_EVENT = 1000,
};

BEGIN_EVENT_TABLE(SocketClient, SocketClient)
	EVT_SOCKET(SOCKET_EVENT, SocketClient::OnSocketEvent)
END_EVENT_TABLE()

SocketClient::SocketClient(const wxString& host, unsigned int port)
{
	wxIPV4address address;
	address.Hostname(host);
	address.Service(port);

	m_client = new wxSocketClient;

	cout << "Connecting to " << host.char_str() << ":" << port;
	cout.flush();
	m_client->Connect(address, false);
	while(!m_client->WaitOnConnect(10)) //secs
	{
		//if the server isn't running when starting this app, this doesn't work,
		//i.e. we won't connect to the server once it's started
		cout << ".";
		cout.flush();
	}
	cout << endl;
	assert(m_client->IsConnected());
	assert(m_client->IsOk());

	cout << "Connected." << endl;

	m_client->SetEventHandler(*this, SOCKET_EVENT);
	m_client->SetNotify(wxSOCKET_LOST_FLAG | wxSOCKET_INPUT_FLAG);
	m_client->SetFlags(wxSOCKET_NOWAIT);
	m_client->Notify(true);
}

SocketClient::~SocketClient()
{
	if(m_client)
		m_client->Destroy();
}

void SocketClient::OnSocketEvent(wxSocketEvent& event)
{
	// I never get here, why not?
	cout << "Got a socket event" << endl;
}




More information about the wx-users mailing list