In Mathematica 11.2, there are new sockets functions that are potentially very useful in network programming. I'm trying to use it to communicate between Mathematica and some external program, but I'm unable to make it work. I'm wondering whether someone could give a simple example demonstrating how socket can be used to receive and send data to other applications.
Here is an example I have tried. I'm using the uWebSockets in a basic C++ application to start a socket and then use Mathematica to connect to that socket.
This is the C++ code:
#include <uWS/uWS.h>
#include <iostream>
using namespace std;
int main()
{
uWS::Hub h;
h.onMessage([](uWS::WebSocket<uWS::SERVER> ws, char *data, size_t length, uWS::OpCode opCode) {
cout << "message received." << endl;
});
h.onConnection([&h](uWS::WebSocket<uWS::SERVER> ws, uWS::HttpRequest req) {
std::cout << "Connected!" << std::endl;
});
h.onDisconnection([&h](uWS::WebSocket<uWS::SERVER> ws, int code, char *message, size_t length) {
ws.close();
std::cout << "Disconnected!" << std::endl;
});
int port = 4567;
if (h.listen(port))
std::cout << "Listening to port " << port << std::endl;
else
{
std::cerr << "Failed to listen to port" << std::endl;
return -1;
}
h.run();
}
And the Mathematica part
socket = SocketConnect["127.0.0.0:4567"]
On one hand, the socket connection is partially successful, otherwise, the SocketConnect
function would have returned the $Failed
. But on the other hand, the "Connected!" message is not outputted in the C++ side indicating that the connection is not successful.
So how to fix this problem and make the socket framework in Mathematica work with other socket libraries?