关于Socket多线程编程
本帖最后由 jlhappy18 于 2012-07-13 11:24:28 编辑 我在Form1的头文件中定义了一个SocketServer
class TForm1 : public TForm
{
__published:// IDE-managed Components
TButton *btn1;
TButton *btn2;
TEdit *edt1;
TEdit *edt2;
TWSocketServer *wscktsrvrTcp; //SocketServer定义
TButton *btnListen;
TTimer *tmr1;
void __fastcall btnListenClick(TObject *Sender);
void __fastcall FormCreate(TObject *Sender);
void __fastcall tmr1Timer(TObject *Sender);
void __fastcall wscktsrvrTcpClientConnect(TObject *Sender,
TWSocketClient *Client, WORD Error);
private:// User declarations
TListenThread *ListenThread;
public:// User declarations
int ThreadIndex;
NewThread *thread[2], *thread1;
TEdit *edt[2];
__fastcall TForm1(TComponent* Owner);
};
//---------------------------------------
然后在btnListenClick事件中开启监听
void __fastcall TForm1::btnListenClick(TObject *Sender)
{
wscktsrvrTcp->Proto = "tcp";
wscktsrvrTcp->Addr = "0.0.0.0";
wscktsrvrTcp->Port = "60000";
wscktsrvrTcp->Listen();
}
//---------------------------------------
在wscktsrvrTcpClientConnect客户端连接事件中开辟新的线程用于处理接收的数据
void __fastcall TForm1::wscktsrvrTcpClientConnect(TObject *Sender,
TWSocketClient *Client, WORD Error)
{
thread[ThreadIndex] = new NewThread(true, edt[ThreadIndex], Client);
thread[ThreadIndex]->Resume();
ThreadIndex++;
}
//---------------------------------------
线程类的cpp文件如下
__fastcall NewThread::NewThread(bool CreateSuspended, TEdit *Edt, TWSocketClient *Client)
: TThread(CreateSuspended)
{
thClient = Client;
edResult = Edt;
Index = 0;
}
//---------------------------------------
void __fastcall NewThread::Execute()
{
thClient->OnDataAvailable = ShowResult;
}
//---------------------------------------
void __fastcall NewThread::ShowResult(TObject *Sender, WORD Error)
{
int i, len;
unsigned char buf[8];
AnsiString str;
ZeroMemory(buf, sizeof(buf));
len = thClient->Receive(buf, 2);
edResult->Text = IntToStr(Index);
if(len>0)
{
Index++;
}
if(Index>1000)
{
Index = 0;
}
Sleep(100);
}
程序通信都正常,但是问题是这种方式没有起到多线程的作用, 当我在发发数据的时候, Form1界面处于瘫痪状态,数据传好后Form1界面才恢复正常, 这不跟单线程一样嘛, 请求高手求指导!!!!
[解决办法]
你这个新线程就起了赋值的作用,所有的操作还是在主线程中执行的,虽然代码在新线程中
要想新线程分担主线程的工作,就要把代码放进Execute()函数中,这个函数里才是线程真正执行的操作