I'm trying to create a communication via WebSocket with a Delphi socket server,
1st Step, readystate
0 - Server receives the WebSocket header.
Step 2, readystate
3 - Already going offline.
Javascript:
var host = 'ws://10.1.1.10:8100'; // SET THIS TO YOUR SERVER
socketWebservice = new WebSocket(host);
socketWebservice.onopen = function(msg) {
socketWebservice.send('LOGON');
alert('entrou');
//setIntSocketSend = setInterval('contSendSocket()', 119000); //confere o Login a cada 4m:58s
};
socketWebservice.onmessage = function(msg) {
on_socket_get(msg.data);
};
socketWebservice.onclose = function(msg) {
// clearInterval(setIntSocketSend);
console.log(msg);
};
Delphi uses the TServerSocket component.
Server Code:
unit uServidor;
interface
uses System.Win.ScktComp, Vcl.StdCtrls, Vcl.Controls, System.Classes, Vcl.Forms,
System.SysUtils;
type
TForm1 = class(TForm)
ServerSocket1: TServerSocket;
ListBox1: TListBox;
Label1: TLabel;
Button1: TButton;
EdtPorta: TEdit;
Label2: TLabel;
BtnConectar: TButton;
ckTodos: TCheckBox;
EdtMensagem: TMemo;
procedure BtnConectarClick(Sender: TObject);
procedure ServerSocket1ClientConnect(Sender: TObject;
Socket: TCustomWinSocket);
procedure Button1Click(Sender: TObject);
procedure ServerSocket1ClientRead(Sender: TObject;
Socket: TCustomWinSocket);
procedure ServerSocket1ClientDisconnect(Sender: TObject;
Socket: TCustomWinSocket);
private
procedure Reconectar;
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.BtnConectarClick(Sender: TObject);
begin
ServerSocket1.Port := StrToInt(EdtPorta.Text);
try
ServerSocket1.Active := true;
BtnConectar.Caption := 'Conectado';
BtnConectar.Enabled := false;
except
raise;
end;
end;
procedure TForm1.ServerSocket1ClientConnect(Sender: TObject;
Socket: TCustomWinSocket);
var
I : Integer;
begin
ListBox1.Items.Clear;
for I := 0 to Pred(ServerSocket1.Socket.ActiveConnections) do
ListBox1.Items.Add('['+ServerSocket1.Socket.Connections[I].RemoteAddress+']');
end;
procedure TForm1.Button1Click(Sender: TObject);
var
I : Integer;
begin
if ckTodos.Checked then
for I := 0 to Pred(ListBox1.Items.Count) do
ServerSocket1.Socket.Connections[I].SendText(EdtMensagem.Lines.Text)
else
ServerSocket1.Socket.Connections[ListBox1.ItemIndex].SendText(EdtMensagem.Lines.Text);
end;
procedure TForm1.ServerSocket1ClientRead(Sender: TObject;
Socket: TCustomWinSocket);
begin
EdtMensagem.TEXT := Socket.ReceiveText;
end;
procedure TForm1.Reconectar;
begin
ServerSocket1.Active := false;
ServerSocket1.Active := true;
end;
procedure TForm1.ServerSocket1ClientDisconnect(Sender: TObject;
Socket: TCustomWinSocket);
var
I : Integer;
Endereco : String;
begin
for I := 0 to Pred(ListBox1.Items.Count) do
begin
Endereco := '['+Socket.RemoteAddress+']';
if Endereco = ListBox1.Items.Strings[I] then
begin
ListBox1.Items.Strings[I] := ListBox1.Items.Strings[I] + ' - DESCONECTADO';
break;
end;
end;
end;
end.