andremussche / delphiwebsockets Goto Github PK
View Code? Open in Web Editor NEWWebsockets and Socket.io for Delphi
Websockets and Socket.io for Delphi
Hi,
Testing the C++ Builder Berlin, all the lib code compiles just fine as far as I can tell but need to translate demo apps to C++, any pointers, I have most of it but this section I'm not sure of the way to make work in C++
server.SocketIO.OnEvent(C_CLIENT_EVENT,
procedure(const ASocket: ISocketIOContext; const aArgument: TSuperArray; const aCallback: ISocketIOCallback)
begin
//show request (threadsafe)
ShowMessageInMainthread('REQUEST: ' + aArgument[0].AsJSon);
//send callback (only if specified!)
if aCallback <> nil then
aCallback.SendResponse( SO(['succes', True]).AsJSon );
end);
the procedure is the problem, I suspect its my lack of understanding on what delphi is doing here that's the issue,
any ideas?
thanks,
david
can i create client with this to connect to Tidtcpserver ?
Hi Andre,
I have started my server as follows:
procedure TForm1.btnCreateWSServerClick(Sender: TObject);
begin
myServer := TIdWebsocketServer.Create(Self);
myServer.DefaultPort := 12345;
myServer.Active := True;
end;
On the html page, I have established connection as follows:
<script type='text/javascript'>
var exampleSocket = new WebSocket('ws://localhost:12345');
exampleSocket.onopen = function(){
console.log('Connection open!');
}
exampleSocket.onclose = function(){
console.log('Connection close!');
}
exampleSocket.onmessage = function(e){
var server_message = e.data;
console.log(server_message);
}
...
</script>
When I connect, the browser logs Connection Open and when I close my Delphi application, browser logs Connection closed. So far so good.
Now I am trying to send a message from the server to the browser client using this
procedure TForm1.btn2Click(Sender: TObject);
begin
myServer.SocketIO.SendToAll('{"data":"hello"}');
end;
but nothing happens on the browser.
what am I doing wrong?
Nirav
I'm trying to register a callback on an external socket. I've got working js code that does just that:
const WebSocket = require('ws');
let authToken = '...';
let user = 'user';
let password = 'pw';
let port = 12345;
let ws = new WebSocket(`ws://${user}:${password}@127.0.0.1:${port}/`, "wamp", {
origin: `http://127.0.0.1:${port}`,
Host: `127.0.0.1:${port}`,
Authorization: `Basic ${authToken}`
});
ws.on('message', (msg) => {
console.log(msg);
});
ws.on('open', () => {
ws.send('[5, "OnJsonApiEvent"]');
});
I'm trying to replicate this in Delphi with your library, but I'm not really sure how to use it, neither to establish the connection, nor to do what the "on" calls do.
This is what I have so far, but it does nothing:
procedure TestSocket;
var client: TIdHTTPWebsocketClient;
begin
client := TIdHTTPWebsocketClient.Create(Self);
client.Port := 12345;
client.Host := '127.0.0.1';
client.Request.CustomHeaders.AddValue('Origin', 'http://127.0.0.1:12345');
client.Request.BasicAuthentication := true;
client.Request.Username := 'user';
client.Request.Password := 'pw';
client.SocketIOCompatible := True;
client.SocketIO.OnSocketIOMsg :=
procedure(const ASocket: ISocketIOContext; const text: string; const aCallback: ISocketIOCallback)
begin
// maybe this is how to register the callback like ws.on('message', ...) ?
Logfile.Log(text);
end;
client.SocketIO.OnEvent('message',
procedure(const ASocket: ISocketIOContext; const aArgument: TSuperArray; const aCallback: ISocketIOCallback)
begin
// or like this ?
Logfile.Log(aArgument[0].AsString);
end);
client.SocketIO.OnEvent('open',
procedure(const ASocket: ISocketIOContext; const aArgument: TSuperArray; const aCallback: ISocketIOCallback)
begin
// this is not called
client.SocketIO.Send('[5, "OnJsonApiEvent"]');
end);
client.Connect;
end;
Do you see anything wrong with that? Any help would be greatly appreciated :)
Hi, i have one problem, i make simple project and i send message from HTML page to Server and Server to HTML, all without problem. Now i send message to Server from Desktop, but when i send message from Server to Desktop i not received this.
Aleread i try use ReadLn but not receive nothing.
Please tell how to implement this in a project, because i'm a lay people in Delphi universe, and this is hard to peoples like me!
i trying to study, i'm new on Delphi and the version i have is XE5!
thanks a lot
Hi,andremussche!,Thanks for you DelphiWebsockets.
I use TIdWebsocketServer for ssl,then can access my host(https://10.11.12.14:443) through internet browser.But use TIdHTTPWebsocketClient access hint: Error while upgrading:"200:HTTP/1.1 200 OK" .
Maybe i can't use it correctly。
My code:
server := TIdWebsocketServer.Create(Self);
server.DefaultPort := 80;
server.Bindings.Clear;
Binding := Server.Bindings.Add;
Binding.IP := '10.11.12.14';
Binding.Port := 443;
IdServerIOHandlerSSLOpenSSL1.SSLOptions.RootCertFile := '....1_root_bundle.crt';
IdServerIOHandlerSSLOpenSSL1.SSLOptions.CertFile := '.com.crt';
IdServerIOHandlerSSLOpenSSL1.SSLOptions.KeyFile := '..key';
server.IOHandler := self.IdServerIOHandlerSSLOpenSSL1;
(Is the author still working int his project?)
I'm trying to use this project's client to access this WS: wss://ws.blinktrade.com/trade/ from this link: https://blinktrade.com/docs/#blinktrade-sdk
But i`m unable to make it work, someone can give me a idea?
A got this error:
Exception class EIdHTTPProtocolException with message 'HTTP/1.1 404 Not Found
PS: I using Delphi 10.2 and XE7, here is my code copied from example:
//{$DEFINE WEBSOCKETSSL} enabled in the wsdefines.pas
client := TIdHTTPWebsocketClient.Create(Self);
client.Port := 443;
client.Host := 'ws.blinktrade.com';
client.WSResourceName := 'trade/';
client.SocketIOCompatible := true;
client.Connect; //error
I suspect the origin os the error comes from this lines in IdHTTPWebsocketClient
// Why is "/socket.io/1/" used? I don't know
{$IFDEF WEBSOCKETSSL}
sURL := Format('https://%s:%d/socket.io/1/', [Host, Port]);
{$ELSE}
sURL := Format('http://%s:%d/socket.io/1/', [Host, Port]);
{$ENDIF}
Thanks for any help!
Hello, I have the ip and port XXX.XXX.XXX.XXX:9009 and I must listen to this port and whenever I hear a request will return:
Event: messageSuccess
{Request: 55, business_id: 5}
I'm trying to use the library but I still do not understand how it works, how could I be using bibliteca for this situation?
My use case is to push messages (based on events) from the server to one or more clients directly - without the need for a client request.
What is the preferred way of accomplishing this behaviour?
Hi,
when trying to use your websockets implementation with openssl, i found a "problem" in the IdIOHandlerWebsocket.pas in the function WriteData. At the very end of this function the data is written to the binding. The binding writes the data directly, bypassing the sslsocket, which crashes the connection.
function TIdIOHandlerWebsocket.WriteData(aData: TIdBytes; aType: TWSDataCode; aFIN, aRSV1, aRSV2, aRSV3: boolean): integer;
...
Result := Binding.Send(bData, ioffset);
Changing the line to
Result := inherited WriteDataToTarget(bdata,iOffset, (Length(bData)-ioffset));
works, though.
It took me some time to figure this out, so maybe this may help others.
best regards,
yves
so i manage to get wss (web socket with SSL). I notice socket.io have conditional define WEBSOCKETSSL, for SSL support. But the normal websocket does not. Can someone please have the
procedure TIdHTTPWebsocketClient.InternalUpgradeToWebsocket
update with the following lines:
{$IFDEF WEBSOCKETSSL}
sURL := Format('https://%s:%d/%s', [Host, Port, WSResourceName]);
{$ELSE}
sURL := Format('http://%s:%d/%s', [Host, Port, WSResourceName]);
{$ENDIF}
How to set the header?
Hi Andre!
I have an electronic device connected to my local WiFi AP and send/recive meassage by other clients with this Html file:
https://github.com/tzapu/WebSocketSerialMonitor/blob/gh-pages/index.html
I type ws://192.168.1.125:81/ws and press connect.
Now I want to send/receive message with Delphi instead of html file.
Your demo work nice on Delphi XE10.1, But I cant find any point to change headers (ws:// , /ws).
Regards.
i am using that way to get some text on server then i try to broadcast back to all connected clients so i try
procedure TForm1.ServerMessageTextReceived(const AContext: TIdServerWSContext;
const aText: string);
var
strm: TStringStream;
begin
ShowMessageInMainthread(aText);
strm := TStringStream.Create('SERVER: ' + aText);
//AContext.IOHandler.WriteLn('goi', IndyTextEncoding_UTF8);
broadcastmessage('goi');
end;
procedure TForm1.broadcastmessage(const text: string);
var
List: TList;
i : integer;
begin
List := Server.Contexts.LockList;
try
for I := 0 to List.Count - 1 do
begin
SendCommand(text);
end;
finally
Server.Contexts.UnlockList;
end;
end;
procedure TForm1.SendCommand(const textprm: String);
begin
//what to do here ?
end;
or better yet can i setup tconnection to each connected client ?as we do in normal tcpserver as example
**TConnection = class(TIdServerContext)
var to define connections as name etc..**
Hi Andre,
I'm trying code in Delphi 10. Works fine while server and client are both Delphi.
But when I try to connect delphi server side from jQuery\Html page I had some problems.
I use jQuery code from https://www.websocket.org/echo.html
When I test the jQuery client with echo server
( var wsUri = "ws://echo.websocket.org/"; )
works fine. ("https://www.websocket.org/echo.html")
But when I tried to connect delphi server
( //var wsUri = "ws://localhost:55555/"; )
jquery code finds the server and connects successfully. Also disconnects if I stop the dlephi server side.
But nothing happens on the server side while client connecting. doent fire OnConnection and doesnt increase the ConnectionCount for example.
EmitEventToAll makes nothing on the jQuery side too.
Do I missing something here?
Regards,
on windows it work fine,can support android?only websocket ,not socket.io
I Using node.js with socket.io last version that include latest version socket.io;
how upgrade to socket version?
I use Delphi 2007. thanks .
Hello, could you please write an example how to connect to "wss://mysite.com" and send a text command like '{"channel":"funny_news"}' to its url "wss://mysite.com/joinhere". Also, would be great to receive text answers from this server
Would appreciate any hints, thank you!
I am still using Delphi 7 pro for a very old product still running at customers.
Can I integrate y implementation inside D7 too?
On a modern browser a typical client would be used by "socket =new Websocket()" (rfc6455) in javascript. Or do I need the socket.io API clientside in browser?
First thanks for this cool websockets library. Good code, Great work!
One problem: When I switch on the WEBSOCKETSSL compiler directive I get the error
[dcc32 Error] IdServerIOHandlerWebsocket.pas(29): E2137 Method 'CreateOpenSSLSocket' not found in base class
The problem is that the due to the following commit:
cdffdd2
It the comment learns me that a change in the IdSSLOpenSSL is needed but the changed IdSSLOpenSSL is not commited.
Can you please commit the changed IdSSLOpenSSL file?
Thanks
Tijmen
I can run the demo(DelphiWebsockets-master\Demo) without SSL;but use SSL hint :[dcc32 Error] IdServerIOHandlerWebsocket.pas(29): E2137 Method 'CreateOpenSSLSocket' not found in base class;
so, How to use in delphi xe7 with SSL,thanks
Hello,
what is the proper way to try to connect again if connection fails? If I call Connect inside OnDisconnected handler, I get access violation in TIdIOHandlerWebsocket.Unlock (Self variable is nil), called from TIdHTTPWebsocketClient.Disconnect.
Hi Andre,
Thanks for creating something that I think should be part of the RemObjects library. We have a client server solution using RemObjects' supertcp or superhttp. We now want to move to browser based clients, but do not want to lose the two-way communication and definitely want to avoid polling in the client.
I have been trying to get the examples to work on Delphi 10.2 but I have not succeeded in getting my target architecture to work. The Delphi client/delphi server setup works, but when I use a browser client, the first call to the server never completes. I get the expected 101 response and then the Network tab of Chrome says: CAUTION: Request is not finished yet. And that remains so forever.
Do you have an idea what could be causing this?
I am using the TROIndyHTTPWebsocketServer, because we need something derived from ROServer.
Kind regards,
Jan
Please explain to me with picture how to instal DelphiWebsockets-master in delphi xe8
i want to use this component for conect to wss://ws.xxxxxxxx
Hello André,
what's the license of DelphiWebsockets?
I am considering using it for a project, but I am having trouble to find the license in the source code:
checking the github repository, the only license I could find is the LGPL stated in superobject.pas, which seems a third-party utility from Henri Gourvest, http://www.progdigy.com, and not the main license for the whole DelphiWebsockets.
Thanks,
Massimiliano Ghilardi
Thank you for your excellent component. I am not sure if it is a bug or not but when from a client app I call Disconnect(), then Connect is called again from the Queue:
TIdWebsocketQueueThread.Execute
TIdWebsocketQueueThread.ProcessQueue
TIdWebsocketMultiReadThread.PingAllChannels
TIdHTTPWebsocketClient.TryUpgradeToWebsocket
TIdHTTPWebsocketClient.InternalUpgradeToWebsocket
TIdHTTPWebsocketClient.Connect
By the way, destroying the component in the client effectively disconnect from the server.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.