Is PacketSender really the best way to test websockets? I don't see it having a support for websockets. How do you set the "Upgrade" and Connection headers? The "Host:" field should also contain the port number, no?
The "address_string" in your Bela program should not the IP of the client, but the endpoint that the client would try to access (e.g.: if you try to connect to 192.168.7.2:8888/address, then the endpoint is "address"). Here's a working version of your code:
#include <Bela.h>
#include <string>
#include <libraries/WSServer/WSServer.h>
WSServer wss;
void wssOnConnect();
void wssOnDisconnect();
void wssOnReceive(const std::string& address, const void* buf, size_t size);
std::string endpoint = "address";
unsigned int sendEveryMs = 1000;
unsigned int sendEvery; // set below based on sampling rate
unsigned int sendEveryCount = 0;
bool setup(BelaContext *context, void *userData)
{
wss.setup(8888);
wss.addAddress(endpoint,
[] (std::string address, void* buf, int size)
{ wssOnReceive(address, buf, size); },
[] (std::string address) { wssOnConnect(); },
[] (std::string address) { wssOnDisconnect(); }
);
sendEvery = context->audioSampleRate * (sendEveryMs * 0.0001f);
return true;
}
void wssOnConnect()
{
printf("Connected\n");
wss.sendNonRt(endpoint.c_str(), "connected");
}
void wssOnDisconnect()
{
printf("Disconnected\n");
}
void wssTaskRT()
{
wss.sendRt(endpoint.c_str(), "RT"); // send something in real-time
}
void wssOnReceive(const std::string& address, const void* buf, size_t size)
{
printf("onreceive: %s %*s\n", address.c_str(), size, (const char*)buf);
}
void render(BelaContext *context, void *userData)
{
for(unsigned int n = 0; n < context->audioFrames; ++n)
{
if(++sendEveryCount >= sendEvery)
{
wss.sendRt(endpoint.c_str(), "test-rt");
rt_printf("Sending test message\n");
sendEveryCount = 0;
}
}
}
void cleanup(BelaContext *context, void *userData)
{}
I tested it by opening a browser window and going to 192.168.7.2:8888 . This, predictably, gives a 404 error (because you are trying to get a webpage instead of connecting to a websocket), but then I can open the javascript console and type:
ws = new WebSocket("ws://192.168.7.2:8888/address"); ws.addEventListener("message", (event) => { console.log("Message from server:", event.data); })
and I will start getting printouts in the browser console (the client) and on the server (the Bela program). If you don't type the two commands on the same line, you'll miss the initial "Message from server: connected" message, but apart from that it should work as expected. You can also send to the server with ws.send("my message") .
As to how to do it with PacketSender, you'll have to figure it out on your own, I am afraid I cannot help with that. What are you doing all of this for, anyhow?