Posted Sun, 04 Oct 2015 08:04:17 GMT in reply to
Zora
Reply
On Sun, 04 Oct 2015 06:15:08 GMT, Zora wrote:
Sorry about the empty topic. I accidentally hit enter after I typed the topic and it posted. I also got a 500 error when I registered my account which was a little weird, given that everything seems to have worked fine in the end.
No problem! I've deleted the other topic. The 500 error turned out to be already fixed in the latest version (I've upgraded now).
Anyways, I'm trying to exchange data between websockets, but I'm not sure how to do this. None of the example code I see on the forums or around the net seems to work because vibe.d has the WebSocket scoped, so I can't add it to a collection or anything.
The most idiomatic example is probably the following, but it's limited to sending data:
https://github.com/rejectedsoftware/vibe.d/tree/master/examples/web_websocket
Basically, you can send messages using the .send()
method as long as .connected
is true
and receive messages using .receiveText()
or .receiveBinary
as long as .waitForData()
returns true
. Now if you need to send data to a web socket from other parts of the code, you could for example use send
/receive
from vibe.core.concurrency
to communicate between the tasks:
Task[] m_socketHandlers;
void onWebSocket(scope WebSocket sock)
{
// add ourself to a list of all web socket handlers
auto thistask = Task.getThis();
m_socketHandlers ~= thistask;
scope (exit) m_socketHandlers = m_socketHandlers.filter!(t => t != thistask).array;
// pass all messages on to the socket
while (true) {
auto msg = receiveOnly!string;
if (!sock.connected) break;
sock.send(msg);
}
}
void sendSomething()
{
foreach (s; m_socketHandlers)
s.send("Hello, World!");
}
It's also possible to start a local task to send and receive concurrently:
void onWebSocket(scope WebSocket sock)
{
// handle writing
auto t = runTask({
while (true) {
auto msg = receiveOnly!string;
if (!sock.connected) break;
sock.send(msg);
}
});
// TODO: add t to m_socketHandlers, or use a similar mechanism
// handle reading
while (sock.waitForData) {
auto msg = sock.receiveText();
// do something with message...
}
// make sure the task doesn't access the scoped WebSocket after the end of the scope
// something else than interrupt() would be cleaner (e.g. send a special "quit" message and then use t.join();)
t.interrupt();
}