synapse socket总结二:tcp与udp通讯示例

对于synapse的tcp应用,最好的示例就是synapse的echo demo(synapse40\source\demo\echo),demo里清晰展现了上节提到的“TCP并发服务器”模型,代码如下:

unit echo;

interface

uses
  Classes, blcksock, synsock;

type
  TTCPEchoDaemon = class(TThread)
  private
    Sock:TTCPBlockSocket;
  public
    Constructor Create;
    Destructor Destroy; override;
    procedure Execute; override;
  end;

  TTCPEchoThrd = class(TThread)
  private
    Sock:TTCPBlockSocket;
    CSock: TSocket;
  public
    Constructor Create (hsock:tSocket);
    procedure Execute; override;
  end;

implementation

{ TEchoDaemon }

Constructor TTCPEchoDaemon.Create;
begin
  inherited create(false);
  sock:=TTCPBlockSocket.create;
  FreeOnTerminate:=true;
end;

Destructor TTCPEchoDaemon.Destroy;
begin
  Sock.free;
end;

procedure TTCPEchoDaemon.Execute;
var
  ClientSock:TSocket;
begin
  with sock do
    begin
      CreateSocket;
      setLinger(true,10000);
      bind('0.0.0.0','8008');
      listen;
      repeat
        if terminated then break;
        if canread(1000) then
          begin
            ClientSock:=accept;
            if lastError=0 then TTCPEchoThrd.create(ClientSock);
          end;
      until false;
    end;
end;

{ TEchoThrd }

Constructor TTCPEchoThrd.Create(Hsock:TSocket);
begin
  inherited create(false);
  Csock := Hsock;
  FreeOnTerminate:=true;
end;

procedure TTCPEchoThrd.Execute;
var
  s: string;
begin
  sock:=TTCPBlockSocket.create;
  try
    Sock.socket:=CSock;
    sock.GetSins;
    with sock do
      begin
        repeat
          if terminated then break;
          s := RecvPacket(60000);
          if lastError<>0 then break;
          SendString(s);
          if lastError<>0 then break;
        until false;
      end;
  finally
    Sock.Free;
  end;
end;

end.

UDP应用则在官方网站的Public Wiki上有一个简单的示例:

procedure TSomeThread.Execute;
var
  Sock:TUDPBlockSocket;
  size:integer;
  buf:string;
begin
  Sock:=TUDPBlockSocket.Create;
  try
    sock.bind('0.0.0.0','port');
    if sock.LastError0 then exit;
    while True do
      begin
        if terminated then break;
	buf := sock.RecvPacket(1000);
	if sock.lasterror=0 then
	  begin
  //        do something with data and prepare response data
            sock.SendString(Buf);
          end;
        sleep(1);
      end;
    sock.CloseSocket;
  finally
    sock.free;
  end;
end;

可以看出,这个一个常用的UDP循环服务器模型。

转载请注明:梧桐树下 » synapse socket总结二:tcp与udp通讯示例

与本文相关文章

发表我的评论

取消评论
表情 插代码

Hi,您需要填写昵称和邮箱!

  • 必填项
  • 必填项