A client connects using the Sockets.connect()
function.
It can then read and write (newline terminated) strings.
The client is
EchoClient.jl illustrates these:
using Sockets
if size(ARGS)[1] < 1
println("Usage: IP hostname")
exit(1)
end
hostname = ARGS[1]
clientside = connect(hostname, 2000)
print("Enter line:")
for line in eachline(stdin)
print("Read line: '$line'\n")
if line == "BYE"
exit(0)
end
write(clientside, string(line, "\n"))
write(stdout, "Echoed: '", readline(clientside, keep=true), "'")
print("\nEnter line:")
end
It can be run in a number of ways such as
julia EchoClient.jl localhost
julia EchoClient.jl 127.0.0.1
but not
julia EchoClient.jl ::1
The implementation currently uses getaddrinfo()
with the
default of IPv4 address only and won't accept a literal IPv6 address.
A server listens to the zero (ANY) address on the port to accept requests. While the socket remains open, it reads the available bytes and writes the resultant vector back to the socket.
The server is EchoServer.jl illustrates these:
using Sockets
server = listen(IPv6(0), 2000)
while true
sock = accept(server)
write(stdout, "Connected")
@async while isopen(sock)
bytes = readavailable(sock)
write(sock, bytes)
end
end
Copyright © Jan Newmarch, jan@newmarch.name
" Network Programming using Java, Go, Python, Rust, JavaScript and Julia"
by
Jan Newmarch
is licensed under a
Creative Commons Attribution-ShareAlike 4.0 International License
.
Based on a work at
https://jan.newmarch.name/NetworkProgramming/
.