以前的贴子:
1.将clientsocket的clienttype设为ctblocking,将serversocket的servertype
设为stThreadBlocking
2.将clientsocket的host和port设为serversocket的IP和端口号
3.自定义线程tdealthread:
TdealThread = class(TServerClientThread)
private
protected
procedure Execute; override;
public
thr:tserverclientwinsocket;
end;
4.在serversocket的serversocketgetthread事件中写入以下语句以便在接到clientsocket
端请求时启动tdealthread线程:
var
myt:tdealthread;
begin
myt:=tdealthread.Create(false,clientsocket) ;
myt.thr :=clientsocket;
socketthread:=myt;
end;
5.在serversocket的procedure TdealThread.Execute中写入每次接到clientsocket请求
时想要完成的动作,举例如:
var
mysockets:twinsocketstream;
rcvbuffer:array[0..299] of char;
sndbuffer:array[0..299] of char;
begin
mysockets:=twinsocketstream.Create (thr,20);
mysockets.WaitForData (1000);
mysockets.Read (rcvbuffer,300);//将client端数据取到rcvbuffer中
//......数据处理,将要发往client端的数据放到sndbuffer中
mysockets.WaitForData (1000);
mysockets.Write(sndbuffer,300);
end;
6.在客户端需要向服务器端提出请求时,执行下面程序:
var
myclientsockets:twinsocketstream;
rcvbuffer:array[0..299] of char;
sndbuffer:array[0..299] of char;
begin
clientsocket.active:=true;
myclientsockets:=twinsocketstream.Create (clientsocket.socket,20);
myclientsockets.WaitForData (1000);
//......将要传送的数据放入sndbuffer中
myclientsockets.write(sndbuffer,300);
myclientsockets.WaitForData (1000);
myclientsockets.read(rcvbuffer,300);//将serversocket发回的数据取到rcvbuffer中
clientsocket.active:=false;
end;
基本框架就是这样了,当然别忘了打开serversocket.
补充:
1.在自定义的线程中最好有循环处理过程:
vStream := TWinSocketStream.Create(ClientSocket, ConnectTimeOut);
while (not Terminated) and ClientSocket.Connected do
begin
//接收报文
....
//发送应答
.....
if ... then
ClientSocket.Close;
end;
ClientSocket.Close;
vStream.Free;
//接收和应答报文的格式自定义,可参考TCP/IP的实现方法
2.在应答前,最好有一小段延时,避免过分频繁的交换数据导致死机
sleep(..)