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

这是wxWidgets论坛的中文版本。在这里,您可以用您的母语汉语讨论上面任一子论坛所涉及的所有关于wxWidgets的话题。欢迎大家参与到对有价值的帖子的中英互译工作中来!
Post Reply
JacquesChen
In need of some credit
In need of some credit
Posts: 7
Joined: Tue Jan 03, 2017 9:33 am

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

Post 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在后台监控特定的端口,这个端口会不停的发送数据过来,会不断的连接,断开,连接,断开
lfjking
Earned some good credits
Earned some good credits
Posts: 102
Joined: Mon Nov 14, 2016 1:35 pm

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

Post by lfjking »

可以直接继承wxthread
然后用wxsocketclient 循环接收处理就可以了。
好像这个帖子好久了。。我在挖坟???? :shock:
Post Reply