Search code examples
typestcptype-conversionjulia

Reading composite type over TCP in Julia


I am trying to send/receive a composite type over TCP. In order to do this I first create listener part :

using Sockets

# my-compiste-type
struct Signal
 min::Array{Float32,1}
 max::Array{Float32,1}
end

listener = listen(12345)
receiver = accept(listener)

read!(receiver, Ref()) # problem !!!

On the other hand, the sender part code :

using Sockets

# my-compiste-type
struct Signal
    min::Array{Float32,1}
    max::Array{Float32,1}
end

s = Signal(rand(0:1, 10), rand(0:1, 10))   # data to send 


client = connect(12345) # connecting to server side
write(client, Ref(s))

Now the problem occurs when I try to read read!(receiver, Ref()) . If I write read!(receiver, Ref(Signal)()) then I get segmentation fault and the program exits. And if I write read!(receiver, Ref(typeof(Signal)()) then I get errors.

What is the right way to send composite data types from sender to receiver ?

I also found a similar question on Julia discourse page but the o.p. solves the issue with UDPSocket. I also tried that but it uses reinterpret function. And reinterpret function does not convert Signal data type to UInt or other types.

Could you help please ?

B.R.

p.s. By the way I am using Julia version 1.0.3.


Solution

  • Using your example, you can use Julia's native serialization capability:

    Sending:

    import Sockets, Serialization
    
    struct Signal # my-compiste-type
        min::Array{Float32,1}
        max::Array{Float32,1}
    end
    
    s = Signal(rand(0:1, 10), rand(0:1, 10)) # data to send 
    client = Sockets.connect(12345) # connecting to server side
    s = Serialization.serialize(client, s) # serialize content
    # ... remember to cleanup IO connections with close
    

    Receiving

    import Sockets, Serialization
    
    struct Signal # my-compiste-type
        min::Array{Float32,1}
        max::Array{Float32,1}
    end
    
    listener = Sockets.listen(12345)    
    receiver = Sockets.accept(listener)
    s = Serialization.deserialize(receiver)
    # ... remember to cleanup IO connections with close
    

    Keep in mind: