Learning Java in 2020 – Beginner – Ridiculously Simple Python Client and a Java Server

Overview reference

Problem

Goal

Make a python socket client send a “hello” message to a waiting java server. Voila!

Pseudo-code

  1. Create a server socket that waits for incoming streams / connection from another address
  2. Send a “hello world” message to the server socket and have the server socket print it out after the connection has been closed

Theoretical Background

Network protocols

Network protocols are a set of rules that defines the communication between two nodes across a network. Types of such protocols are TCP/IP for transferring data across the internet, FTP for transferring files, SMTP for emails, DNS for converting human readable domain names (e.g. google.com) to IP addresses ( 172.217.23.132:443 ), etc.

What is a data packet

Before you send your gameintstructions.txt file to your friend’s machine, a protocol has to be selected. After selection, the protocol processes your file and breaks it into bytes ( i guess) and sends it to your friend’s machine ( protocol:ip address:port). These chunks are referred to as packets. Keep in mind that these packets do not only contain the user’s data which is held in the packet’s payload ( in this case gameinstructions.txt) but also more information for the journey to your friend’s machine.This means, source and destination ip address, error codes etc. So basically, this web page you are reading right now was sent to your browser in the form of mini-packets.

Anatomy of a network packet

Based on this article a network packet is made up of three parts, namely: the header, payload and the trailer. The header carries information about the source of the packet ( source address), its destination ( destination address), the set of rules for handling the packet ( protocol), the number of packets of the entire data and its position in the list. On the other hand, payload is the actual message to be transmitted, which could be a video, an image or even a text message. The trailer indicates to the recipient that the current packet is the end of the file ( ~ the last packet).

But how does the receiver ( here your friend’s computer) know when the incoming packet is the last packet?

The trailer portion of a network packet, which may vary in structure based on the network, informs the recipient.

Solution

Java Server Socket

This socket will randomly pick an available port, so we do not need to add “valid” port as an argument to the ServerSocket constructor. Wait ,but isn’t 0 a port ? Based on articles I read online, some say it is nonexistent officially, others say it exists but is reserved. Luckily, the ServerSocket constructor randomly selects an available port if only the argument is 0.

The following line simply prints out the IP address of the socket. Since the socket is from the local machine, the address is most likely going to look like this: “127.0.0.1:(randomly selected available port)”.

private void connectToPort() {
		
		try {
			ServerSocket serversocket = new ServerSocket(0);
			System.out.println(serversocket.getLocalSocketAddress());
			Socket s = serversocket.accept();
			InputStream is =s.getInputStream();
			byte[] list = is.readAllBytes();
			System.out.println(list.toString());
			String message  = new String(list,  StandardCharsets.UTF_8);
			System.out.println(message);
			serversocket.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
}

After creating our server socket, we wait for connection or input stream by calling the accept method. So if some port/ service/ client in our local machine makes a TCP connection call to the address printed previously, this server socket will catch it. The socket returned as a result of the connection listens to all the messages sent over by that port until that port closes the connection.

Once the connection is closed, our server socket converts the byte array ( input stream) into a string based on the utf-8 encoding rules. Afterwhich, the generated string is printed out and the server socket is closed.

Python Client

By using the socket library, we can create a socket object by calling the socket method. socket.AF_INET indicates the IP address format of the socket, while the socket.SOCK_STREAM tells the socket to accept or send data packets based on the TCP protocol. An alternative would be socket.SOCK_DGRAM, if you want to send data following the UDP protocol. Read here.

import socket


def PythonClient():
	s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	s.connect(("localhost", 49419))
	print(s.getsockname())
	message = bytes("Hello my name is Comfort Ajala", "utf-8")
	s.send(message)
	s.close()
	return 
	
PythonClient()

Once the socket is generated error-free, we connect to our java server socket. But how do we know what the java server socket address is ? Simple, run the java server socket code so you can see its address. Then fill the tuple values of the s.connect method accordingly.

Similar to the Java socket, we print out the python socket address. Note, an error is thrown if you call the getsockname method before the s.connect call.( would be appreciated if someone provided an explanation for this)

Finally we send the message in bytes and close the connection afterwards.

Result

Author Notes

This is most likely not the cleanest implementation, just a heads up.

Links

  1. Anatomy of a data packet
  2. Network protocol definition
  3. Network data packet
  4. IP packets types
  5. Byte array to string
  6. OSI Model beautifully explained