how to connect a python client to java server with TCP sockets

Hello folks,

this time I would like to share my knowledge about connecting a java server program with a python client program using TCP socket communication. Yesterday I spent quite a lot time to get this running, by reading several tutorials on socket programming but I only got java-java or python-python communication running smoothly.

Ok, my key problem was that java expects the end-of-line sign (EOL) in some way, that the python examples didn’t supply. It all depends on the combination of what kind of functions are used to read and write from and to the sockets.

I wanna start with my python client:

#!/usr/bin/env python

import socket

HOST = "localhost"
PORT = 8080

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((HOST, PORT))

sock.sendall("Hello\n")
data = sock.recv(1024)
print "1)", data

if ( data == "olleH\n" ):
	sock.sendall("Bye\n")
	data = sock.recv(1024)
	print "2)", data

	if (data == "eyB}\n"):
		sock.close()
		print "Socket closed"

As you can see it is stripped down to the very essence that is necessary for socket communication. I’ve implemented a very basic protocol for letting client and server exchange some messages.

We start by importing “socket” as we need this package for socket creation and communication. Then we create two variables holding the host and the port we want to connect to. If you wanna try that over a network just replace localhost with the servers IP address.

Then we create a socket object “sock” and establish a connection to the given server. As we are the initiator we send a “Hello\n” to the server and wait for the response afterwards.

So this “Hello\n” message holds the first trap I tipped over while implementing that: on the java side we will use the function “readLine()” to read the input on the server socket from the client and readLine() expects an EOL sign to continue, namely it wants a ‘\n‘! So you have to provide that on the senders side otherwise you will run into trouble.

The server is going to respond something and if that is equal to “olleH\n” we branch to the if statement sending a “Bye\n” and waiting again for the response. Typically you would close now the socket, because the client said goodbye and normally no server response is expected any more, but here the client waits until the server also sends “eyb\n” and then closes the socket (second if block).

Just one word on the sock.recv(1024): I use here the normal python function and the number specifies the amount of bytes that can be handled in the buffer. For further details on that please have a look at http://docs.python.org/library/socket.html.

I think the client is explained enough and it isn’t so complicated either, or? Now lets have a look at the server:

import java.io.*;
import java.net.*;

class JavaServer {
	public static void main(String args[]) throws Exception {
		String fromClient;
		String toClient;

		ServerSocket server = new ServerSocket(8080);
		System.out.println("wait for connection on port 8080");

		boolean run = true;
		while(run) {
			Socket client = server.accept();
			System.out.println("got connection on port 8080");
			BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
			PrintWriter out = new PrintWriter(client.getOutputStream(),true);

			fromClient = in.readLine();
			System.out.println("received: " + fromClient);

			if(fromClient.equals("Hello")) {
				toClient = "olleH";
				System.out.println("send olleH");
				out.println(toClient);
				fromClient = in.readLine();
				System.out.println("received: " + fromClient);

				if(fromClient.equals("Bye")) {
					toClient = "eyB";
					System.out.println("send eyB");
					out.println(toClient);
					client.close();
					run = false;
					System.out.println("socket closed");
				}
			}
		}
		System.exit(0);
	}
}

It’s the nature of java that it requires some more code to realise a server application. First we import the all packages for Input/Output (java.io.*) and all from the network package (java.net.*). Then we define the JavaServer class and give it a main method that is executed when the program is started.

We create two String objects which will hold the messages we read/write from/to the socket. Then we create a ServerSocket object that is listening on port 8080 and we enter a while loop to listen for incoming connections.

This loop is blocked at

Socket client = server.accept();

until a client connects to the server on this port. You also could specify a socket timeout, so that you program continues, but that’s not what we want here. If a client has connected we create a BufferedReader (in) and a PrintWriter (out) to read from the socket and write to the socket. Java provides several different functions for that, I used those and they work as expected. Then we read some input on the socket with

fromClient = in.readLine();

and here comes the ‘\n‘ into play as mentioned previously: readLine expects ‘\n’ to signal the end-of-line (EOL).

The following steps are more or less the same as on the python client: We compare the input against “Hello“, if that’s the case we send back “olleH” to the client.

! Important: we use here the println(…) function. This automatically sends an EOL along with the provided string in contrast to the print(…) function! You could also use the print() function BUT then you have to append a ‘\n‘ to your string sent to the client!

The rest is not very interesting despite of: if we get in the second if statement we send the “eyB” to the client, close the socket to the client and set the variable run = false to stop the while loop. You could use this in case your server receives a quit signal to stop the application.

So that was a very brief description on how you can connect a java server with a python client via TCP sockets. It all stands and falls with the use of the proper EOL signal! Usually you would create a thread for each incoming and accepted connection and let the thread handle the protocol with the client so the server is up and ready to accept the next connection, but that was not the focus of this post.

If you found that helpful leave me a comment and if you are interested in a threaded server let me know and I check if I can post some basic example.

Cheers norbert ๐Ÿ˜‰

10 thoughts on “how to connect a python client to java server with TCP sockets

    • If this helped you, you are welcome ๐Ÿ˜‰ Thx for you comment, that motivates to write more about those stuff ^_^

  1. You are awesome!! This was very useful for the project I’m working on and it saved me a lot of time… Thanks for the valuable information

  2. This was very helpful! Saved me a lot of time searching the internet. One question thought, I am trying to send a user typed message by doing:
    message = raw_input(“Enter A Message: “)
    sock.sendall(message+”\n”)
    but for some reason that won’t work.
    Any advice?
    Thanks!

    • no problem … I also had issues with stuff like that … that was the reason I wrote this tutorial … to share what I have learned ๐Ÿ˜‰

  3. Very usefull stuff. I could finish my application with this tutorial, great and Thanks. ๐Ÿ™‚

Comments are closed.