Delphi 5 Tserversocket和Tclientsocket的简单示例

时间:2018-09-07 10:50:29

标签: delphi

尽可能在 DELPHI 5 中提供示例

让我们说以下代码。一个简单的tclientsocket与tserver套接字通信。 如果来自tclientsocket的请求是在事件tserversocket1onReadClient上的数据处理之后发出的,则一切正常。 但是,当我在处理过程中途从socketclient1收到一个新请求并且还没有完成我的处理过程时,我将如何绕过该问题呢?

  1. 我是否必须在ServerType中实现它: stThreadBlocking
  2. 我必须创建一个线程来执行该过程吗?
  3. 这是一种更好的方法来简化此操作吗?

我的tclientsocket字符串消息不会超过255个字符。

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  StdCtrls, ScktComp;

type
  TForm1 = class(TForm)
    ClientSocket1: TClientSocket;
    Button1: TButton;
    ServerSocket1: TServerSocket;
    procedure Button1Click(Sender: TObject);
    procedure ClientSocket1Error(Sender: TObject; Socket: TCustomWinSocket;ErrorEvent: TErrorEvent; var ErrorCode: Integer);
    procedure ServerSocket1ClientError(Sender: TObject;Socket: TCustomWinSocket; ErrorEvent: TErrorEvent;var ErrorCode: Integer);
    procedure ServerSocket1ClientRead(Sender: TObject;
      Socket: TCustomWinSocket);
  private
  public
  end;

var
  Form1: TForm1;

implementation

{$R *.DFM}

procedure TForm1.Button1Click(Sender: TObject);
begin
with Serversocket1 do
begin
Active:=false;
ServerType:=stNonBlocking;
port:=5052;
Active:=true;
end;

with ClientSocket1 do
begin
active:=false;
port:=5052;
Address:='127.0.0.1';
host:='127.0.0.1';
active:=true;
end;
end;

procedure TForm1.ClientSocket1Error(Sender: TObject;
  Socket: TCustomWinSocket; ErrorEvent: TErrorEvent;
  var ErrorCode: Integer);
begin
errorcode:=0;
end;

procedure TForm1.ServerSocket1ClientError(Sender: TObject;
  Socket: TCustomWinSocket; ErrorEvent: TErrorEvent;
  var ErrorCode: Integer);
begin
errorcode:=0;
end;

procedure TForm1.ServerSocket1ClientRead(Sender: TObject;Socket: TCustomWinSocket);
var mydata:String;
begin
mydata:=socket.ReceiveText;
///Proceccing my data now
//Line 1
//Line 2
//Line 3
//Line 4  <---- ie. when i am proccessing line 4 a new Request from clientsocket1 arrives
//Line 5
end;

end.

1 个答案:

答案 0 :(得分:1)

您描述的情况不会发生。 ServerSocket1ClientRead事件处理程序执行时,不会以可重入的方式调用它。好吧,除非您要致电Application.ProcessMessages。所以,不要那样做!