WebSocket-scgWebSocket For Delphi
sgcWebSocket 组件作为商业组件,相对比较成熟,今天研究一下,参考官网地址:https://www.esegece.com
-
服务端
sgcWebSocketServer
属性:Bindings 增加监听socket 配置监听Ip地址和端口
Active 激活监听功能
方法:OnConnect 客户端连接到服务端时触发的方法
OnMessage 收到客户端消息时触发的方法
至此,一个简单的WebSocket服务端已经实现了。
源码:
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, sgcBase_Classes, sgcSocket_Classes, sgcTCP_Classes,
sgcWebSocket_Classes, sgcWebSocket_Server, sgcWebSocket, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
sgcWebSocketServer1: TsgcWebSocketServer;
procedure Button1Click(Sender: TObject);
procedure sgcWebSocketServer1Message(Connection: TsgcWSConnection;
const Text: String);
procedure sgcWebSocketServer1Connect(Connection: TsgcWSConnection);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
begin
sgcWebSocketServer1.Active:=True;
Button1.Caption:='Stop';
end;
procedure TForm1.sgcWebSocketServer1Message(Connection: TsgcWSConnection;
const Text: String);
begin
ShowMessage('Message Received From Client:'+text);
end;
procedure TForm1.sgcWebSocketServer1Connect(Connection: TsgcWSConnection);
begin
Caption:='Connected!';
end;
end.
-
客户端
sgcWebSocketClient
属性:Host 服务端地址
Port 服务端端口
Active 激活连接
事件:WriteData() 发送数据
源码
unit Unit2;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, sgcBase_Classes, sgcSocket_Classes, sgcTCP_Classes,
sgcWebSocket_Classes, sgcWebSocket_Classes_Indy, sgcWebSocket_Client,
sgcWebSocket;
type
TForm2 = class(TForm)
sgcWebSocketClient1: TsgcWebSocketClient;
Button1: TButton;
Edit1: TEdit;
Button2: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form2: TForm2;
implementation
{$R *.dfm}
procedure TForm2.Button1Click(Sender: TObject);
begin
sgcWebSocketClient1.Active:=True;
Button1.Enabled:=False;
Button2.Enabled:=True;
end;
procedure TForm2.Button2Click(Sender: TObject);
begin
sgcWebSocketClient1.WriteData('Hello Server From VCL Client');
end;
end.