2
$\begingroup$

I try to implement sockets from java.net.ServerSocket in Mathematica. I execute this code step by step:

Needs["JLink`"]
InstallJava[]

(* LinkObject[..] *)

After this I have to create server socket:

serverSocket = JavaNew["java.net.ServerSocket", 8080]
socket = serverSocket@accept[]

(* 
    << JavaObject[java.net.ServerSocket] >>
    << JavaObject[java.net.Socket] >> // after opening localhost:8080
*)

Now you need to open the page http://localhost:8080. This page will be in a state of constant expectation, until an answer is sent. So, now I can read data from the socket:

inputStream = socket@getInputStream[]
length = inputStream@available[]
(bytes = Table[inputStream@read[], {length - 1}]) // Short

(*
    << JavaObject[java.net.SocketInputStream] >>
    320
    {71, 69, 84, 32, 47, 32, 72, 84, 84, 80, 47, 49, 46, 49, 13, 10, 65, \
    <<286>>, 110, 58, 32, 75, 101, 101, 112, 45, 65, 108, 105, 118, 101, \
    13, 10, 13}
*)

But, if you refresh the page http://localhost:8080 during reading from the inputStream then get the exception. Reading the last of bytes after refresh the page:

inputStream@read[]

(* $Failed *)

During evaluation of In[..]:= Java::excptn: A Java exception occurred: java.net.SocketException: Connection reset at java.net.SocketInputStream.read(SocketInputStream.java:154) at java.net.SocketInputStream.read(SocketInputStream.java:141) at java.net.SocketInputStream.read(SocketInputStream.java:223).

The same will happen when you try to write to OutputStream after the page is updated. How can I lock a socket while reading a request and writing a response? How can I create a query queue, where the requests will come in at the time the socket is busy? Thank you in advance.

$\endgroup$

Your Answer

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

Browse other questions tagged or ask your own question.