C++Builder-使用TIdTCPServer以编程方式创建TCP服务器连接

C++ Builder - Creating a TCP Server Connection programmatically with TIdTCPServer

本文关键字:创建 TCP 服务器 连接 方式 编程 使用 TIdTCPServer C++Builder-      更新时间:2023-10-16

我需要用TIdTCPServer组件实现TCP Server连接。我已经用GUI(拖放)和它的工作方式做过了。但我需要拆分表单和TCP实现。到目前为止,我看到的示例代码总是使用TIdTCPServer作为TForm类的成员。(拖放的结果)。

如何调用我从TForm实现的TCPConnection

TCPConnection CConnection = new TCPConnection(Owner, this);

以下是我尝试创建TCP Server连接的方法。

TCPConnection::TCPConnection(TComponent* Owner, TForm4* TSuperForm){
    IdTCPServer1 = new TIdTCPServer(Owner);
    IdTCPServer1->Bindings->Clear();
    //IdTCPServer1->Bindings->Add()->SetBinding("10.10.2.103", 774);
    IdTCPServer1->OnConnect = (TIdServerThreadEvent)(&OnConnect);
    IdTCPServer1->OnExecute = (TIdServerThreadEvent)&OnExecute;
    IdTCPServer1->OnDisconnect = (TIdServerThreadEvent)&OnConnect;
    IdTCPServer1->OnException =  (TIdServerThreadExceptionEvent)&OnException;
     IdTCPServer1->DefaultPort = 774;
    IdTCPServer1->Bindings->Add();
    IdTCPServer1->Bindings->Items[0]->IP="10.10.2.103";
    IdTCPServer1->Bindings->Items[0]->Port=774; 

    IdTCPServer1->ListenQueue = 15;
    IdTCPServer1->MaxConnections = 15;
    IdTCPServer1->TerminateWaitTime = 5000;
    IdTCPServer1->Active = true;

    this->TSuperForm = TSuperForm;
}

到目前为止,代码是有效的。但当我试图到达上下文时,连接丢失,throws是一个异常

void TCPConnection::OnConnect(TIdContext *AContext){
    String IP = AContext->Binding()->PeerIP;
}
void TCPConnection::OnException(TIdContext *AContext, Exception *AException)
{
    ShowMessage("Error:" + AException->ToString());    
}

ErrorTIdTaskThreadWork(我会编辑错误,可能是错误的)如果我不尝试访问AContext,连接将保持不变。

可能是线程、锁定列表。。。

有什么建议吗?

那些函数类型转换看起来很臭。您确定已将函数定义为__fastcall吗,因为根本不需要函数类型转换。

如果定义正确的话,这应该就是你所需要的。

IdTCPServer1->OnConnect = &OnConnect;
// ... etc...

这就是我所做的:

TIdTCPServer *TCPServer = new TIdTCPServer( this );
TCPServer->Active = false;
TCPServer->OnExecute = MyExecute;
TCPServer->DefaultPort = XXX;
TCPServer->Active = true;

然后我的MyExecute调用定义如下:

void __fastcall MyExecute( TIdContext* AContext );

其他回调也以相同的方式处理,不要忘记__fastcall,它应该可以工作。