Page 1 of 1

如何在wxThread里面使用wxSocketBase接收事件呢?

Posted: Sun May 21, 2017 10:44 pm
by JacquesChen
这是我现在的代码,我想通过一个wxThread来监听端口,但是我不知道怎么在wxThread里面把事件关联上。我原来的代码是在一个窗口里面实现的,现在我想知道咱们把窗口里面的这部分代码移植到wxThread里面

Code: Select all

//DialogRealTimeMonitorDeform.h
#ifndef __DialogRealTimeMonitorDeform__
#define __DialogRealTimeMonitorDeform__

#include <wx/wx.h>  
#include <wx/socket.h>
#include "GuiBase/DialogRealTimeMonitorDeformBase.h"

class DialogRealTimeMonitorDeform : public DialogRealTimeMonitorDeformBase
{
public:
	DialogRealTimeMonitorDeform(wxWindow* Parent, int PortIn, wxString IPIn);
	void OnServerEvent(wxSocketEvent& event);
	void OnSocketEvent(wxSocketEvent& event);

private:
	int Port;
	wxString IP;

	wxSocketServer *Server;
	DECLARE_EVENT_TABLE()
};

#endif

Code: Select all

//DialogRealTimeMonitorDeform.cpp
#include "DialogRealTimeMonitorDeform.h"

enum {
	SERVER_ID = 100,
	SOCKET_ID
};

BEGIN_EVENT_TABLE(DialogRealTimeMonitorDeform, wxDialog)
EVT_THREAD(SERVER_ID, DialogRealTimeMonitorDeform::OnServerEvent)
EVT_THREAD(SOCKET_ID, DialogRealTimeMonitorDeform::OnSocketEvent)
END_EVENT_TABLE()

DialogRealTimeMonitorDeform::DialogRealTimeMonitorDeform(wxWindow* Parent, int PortIn, wxString IPIn) : DialogRealTimeMonitorDeformBase(Parent)
{
	Port = PortIn;
	IP = IPIn;

	wxIPV4address Addr;
	Addr.Hostname(IP);
	Addr.Service(Port);
	Server = new wxSocketServer(Addr);
	if (!Server->Ok())
	{
		wxMessageBox(wxT("Listen Port Fail!/n"));
		return;
	}
	Server->SetEventHandler(*this, SERVER_ID);
	Server->SetNotify(wxSOCKET_CONNECTION_FLAG);
	Server->Notify(true);
}

void DialogRealTimeMonitorDeform::OnServerEvent(wxSocketEvent& event)
{
	wxSocketBase *Sock;
	Sock = Server->Accept(false);
	Sock->SetEventHandler(*this, SOCKET_ID);
	Sock->SetNotify(wxSOCKET_INPUT_FLAG | wxSOCKET_LOST_FLAG);
	Sock->Notify(true);
}

void DialogRealTimeMonitorDeform::OnSocketEvent(wxSocketEvent& event)
{
	wxSocketBase *Sock = event.GetSocket();
	switch (event.GetSocketEvent())
	{
	case wxSOCKET_INPUT:
	{
		Sock->SetNotify(wxSOCKET_LOST_FLAG);
		char *Buff;
		Sock->SetFlags(wxSOCKET_WAITALL);
		Buff = new char[8];
		Sock->Read(Buff, 8);
		void *PV = Buff;
		double *PD=NULL;
		PD = (double *)PV;
		m_text->AppendText(wxString::wxString(F.ToString(*PD)) + wxT("\n"));

		Sock->SetNotify(wxSOCKET_LOST_FLAG | wxSOCKET_INPUT_FLAG);
		break;
	}
	case wxSOCKET_LOST:
	{
		Sock->Destroy();
		break;
	}
	default:;
	}
}

wx里资料网上太少了,其实我的目的很简单,就是想用一个wxThread在后台监控特定的端口,这个端口会不停的发送数据过来,会不断的连接,断开,连接,断开

Re: 如何在wxThread里面使用wxSocketBase接收事件呢?

Posted: Mon Jan 22, 2018 10:03 am
by lfjking
可以直接继承wxthread
然后用wxsocketclient 循环接收处理就可以了。
好像这个帖子好久了。。我在挖坟???? :shock: