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) {
    std::cout << "Disconnected!" << std::endl;
  int port = 4567;
  if (h.listen(port))
    std::cout << "Listening to port " << port << std::endl;
    std::cerr << "Failed to listen to port" << std::endl;
    return -1;

And the Mathematica part

socket = SocketConnect[""]

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?


1 Answer 1


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

     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}];
  While[txt =!= EndOfFile,
   txt = ReadString[socket, "\[RawEscape][H"]
   ], Close[socket]

Mathematica graphics

enter image description here


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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