网络:这个accept怎么用?
我是这样,服务端套字节初始化后,建立一个线程
void __fastcall Tmyheard::Execute()
{
.
.
.
TList *ChreadList=new TList;
while(1)
{
Sleep(0);
my_accept();//等待连接
client_hread=new Tclient_head(true); //建立客户机连接线程
ChreadList-> Add(client_hread); //保存新建线程
client_hread-> FreeOnTerminate=true; //自动结束线程
client_hread-> Resume(); //启动线程
}
}
同一台客户机连接上一次后,断开再连接,就连接不上了,客户机第二次连接提示网络错误,如何解决?
[解决办法]
你的Tmyheard是一直运行的吧?
[解决办法]
这段代码有点奇怪,已经设置client_hread-> FreeOnTerminate=true;了,然后又加到了线程列表里ChreadList-> Add(client_hread); .
如果client_hread自动释放了,ChreadList里的相应项不是无效啦?
也许client_hread的代码里有什么机关?
或者楼主直接用Indy组件吧
[解决办法]
我觉得楼主的代码跟我的有点像,发出来给你参考参考
class PACKAGE TMYConnectSock : public TObject{
private:
fd_set FDSET;
protected:
public:
SOCKET m_Sock;
struct sockaddr_in Clientaddr;
int addrLen;
int __fastcall Read(char *buf,int DataLen);
bool __fastcall Send(char *buf,int Len);
__fastcall TMYConnectSock();
__fastcall ~TMYConnectSock();
};
//Class TMYServer
class PACKAGE TMYServer : public TObject{
private:
SOCKET ListenSocket;
struct sockaddr_in Serveraddr;
protected:
public:
bool __fastcall CreateServerSocket();
void __fastcall CloseServer();
bool __fastcall Listen(int ConnectCount);
bool __fastcall Bind();
TMYConnectSock* __fastcall Accept();
__fastcall TMYServer(struct sockaddr_in addr);
__fastcall ~TMYServer();
};
class TServerData : public TObject
{
public:
bool Synchronous;
__fastcall TServerData();
__fastcall ~TServerData();
};
//class TClientData
class TClientData : public TObject
{
public:
TMYConnectSock *ConnectSock;
__fastcall TClientData(TMYConnectSock *Sock);
__fastcall ~TClientData();
};
//TConnectThread
class TConnectThread : public TThread
{
private:
TServerData *ServerData;
TClientData *ClientData;
protected:
void __fastcall Execute();
public:
__fastcall TConnectThread(bool CreateSuspended,TClientData *Data1,TServerData *Data2);
__fastcall ~TConnectThread();
};
//TListenThread
class TListenThread : public TThread
{
private:
int FListenCount;
TList *DelThread;
TMYServer *ListenServer;
protected:
void __fastcall Execute();
public:
TServerData *ServerData;
__fastcall TListenThread(bool CreateSuspended,int ListenPort,int ListenCount);
__fastcall ~TListenThread();
};
void __fastcall TListenThread::Execute()
{
//---- Place thread code here ----
if(!ListenServer-> CreateServerSocket()){
Application-> MessageBoxA( "创建Server失败! ", "提示 ",0);
return;
}
if(!ListenServer-> Bind()){
Application-> MessageBoxA( "绑定端口失败! ", "提示 ",0);
return;
}
if(!ListenServer-> Listen(FListenCount)){
Application-> MessageBoxA( "监听服务失败! ", "提示 ",0);
WSACleanup();
return;
}
while(!Terminated){
Sleep(10);
TClientData *ClientData = NULL;
TMYConnectSock *ConnectSock = NULL;
if((ConnectSock = ListenServer-> Accept()) != NULL ){
ClientData = new TClientData(ConnectSock);
TConnectThread *Ls = new TConnectThread(true,ClientData,ServerData);
while(ServerData-> Synchronous) Sleep(50);
ServerData-> Synchronous = true;
ServerData-> ClientDataList-> Add(ClientData);
ServerData-> Synchronous = false;
}
}
}