10
$\begingroup$

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"]

enter image description here

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?

$\endgroup$
13
$\begingroup$

This is the best use of SocketConnect that I can think for now.

Dynamic[Framed@TextCell[
   Text[Style[
     txt, LineSpacing -> {0.5, 0}, FontFamily -> "Courier", 
     TextJustification -> 0]], PageWidth -> 180
   , Background -> RGBColor[0, 0, Rational[8, 27]], FontColor -> White
   ]]

socket = SocketConnect[{"towel.blinkenlights.nl", 23}];
CheckAbort[
  While[txt =!= EndOfFile,
   txt = ReadString[socket, "\[RawEscape][H"]
   ], Close[socket]
  ];
Close[socket]

Mathematica graphics

enter image description here

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.