📄 myclient.cpp
字号:
//---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
#include "ClientC.h"
#include "MyClient.h"
#pragma package(smart_init)
const int SMALLLEN = 255;
//---------------------------------------------------------------------------
__fastcall MyClient::MyClient(bool CreateSuspended)
: TThread(CreateSuspended)
{
FreeOnTerminate=true;
}
//---------------------------------------------------------------------------
void __fastcall MyClient::Execute()
{
char GetStr;
String RevStr;
char buf[1024+1];
try{
while(ClientFrm->ClientSocket1->Active==true)
{
memset(buf,0,sizeof(buf));
if(ReceiveStr(buf,1024)>0)
{
RevStr=String(buf);
AddMessage(RevStr);
}
RevStr="";
}
}
catch(...)
{
return;
}
ClientFrm->Button3->Click();
ClientFrm->Memo1->Lines->Add("已与服务器断开连接...");
}
//---------------------------------------------------------------------------
int __fastcall MyClient::ReceiveStr(char * _Buf,int length) //接收数据
{
if(length<=0) return 0;
int aLen=0;
int pos=0;
char aBuf[255];
int smalllen=0;
if(length<=smalllen)
smalllen=length;
else
smalllen=SMALLLEN;
TWinSocketStream *pStream;
DWORD beginTick;
beginTick=GetTickCount();
while(ClientFrm->ClientSocket1->Active==true && GetTickCount()-beginTick<200);
try{
pStream = new TWinSocketStream(ClientFrm->ClientSocket1->Socket, 1000);
try{
if (pStream->WaitForData(600000)){
while(pStream->WaitForData(100))
{
Application->ProcessMessages();
if((aLen=pStream->Read(aBuf,smalllen)) == 0)
{
ClientFrm->ClientSocket1->Close();
break;
}
else{
aBuf[aLen]=0;
memcpy(_Buf+pos,aBuf,aLen);
pos+=aLen;
if(pos>=length)
break;
if(length-pos<smalllen) //promise get right byte no more no less
smalllen=length-pos;
}
}
}
else ClientFrm->ClientSocket1->Close();
}
__finally{
delete pStream;
}
}
catch(Exception &E){
Application->HandleException(this);
}
return pos;
}
//---------------------------------------------------------------------------
void __fastcall MyClient::AddMessage(AnsiString Str) //将接收到的数据加入Memo1中
{
ClientFrm->Memo1->Lines->Add(Str);
}
//---------------------------------------------------------------------------
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -