This is an echo server that returns the input in uppercase. If I send hello
I receive back HELLO
.
Nothing crazy going on. The atom, future, loop is how I managed it to keep running forever but have a way to stop it.
To test I can use nc
.
The above connects to the IP/Port over UTC. Then I can type something press Enter
and it shows the response.
The Java standard library has the package java.net
. Inside it we can find these three classes that I used:
It represents an IP address.
It represents a socket for sending and receiving datagram packets. It’s used for connectionless packet delivery.
Key methods:
send(DatagramPacket p)
: sends a datagram packetreceive(DatagramPacket p)
: receives a datagram packetbind(SocketAddress addr)
: binds the socket to a local addressclose()
: closes the socketIn my implementation I didn’t need to use bind
because the constructor already does the binding. I also didn’t have to close because I used with-open
which mimics Java’s try-with-resources.
It contains the data to be send or received, along with the source or destination IP address and port number.
Main constructors:
DatagramPacket(byte[] buf, int length
: Constructs a DatagramPacket for receiving packets.DatagramPacket(byte[] buf, int length, InetAddress address, int port)
: Constructs a DatagramPacket for sending packets.