0

I have a Java application that has a socket listener and listens for TCP events over a specific port, lets say 6500. When the data is received, it typecasts it to a specific java object - EventObj, which has certain fields. For example - EventObj.java

public class EventObj {
   private String firstName;
   private String lastName ;
   // setters and getters 
}

Here is a snippet of the code that receives data over the socket and typecasts it EventObj -

    Socket clientSocket = null;
    while (keepRunning) {
      try {
            clientSocket = null;
            //wait for an incoming call
            clientSocket = serverSocket.accept();
      } catch (IOException e) {
        // log error
      }

      if(clientSocket == null){
         continue;
      }

      ObjectOutputStream objectOutputStream = null;
      ObjectInputStream objectInputStream = null;
      EventObj event = null;
      try{
            objectInputStream = new 
            ObjectInputStream(clientSocket.getInputStream());
            objectOutputStream = new ObjectOutputStream(clientSocket.getOutputStream());

            event = (EventObj) objectInputStream.readObject();
            /// other parts of the code
      }
      //// other parts of the code
  }

If I were to sent a message over a socket connection from Python, how can I create an instance of EventObj in Python and send it over to my Java application so the serialization doesn't fail.

Here is my Python code -

#!/usr/bin/env python

import socket

HOST = "localhost"
PORT = 6502

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

sock.sendall("I NEED TO SEND MY SERIALIZED OBJECT SO JAVA UNDERSTANDS IT")

Any advice?

jagamot
  • 5,348
  • 18
  • 59
  • 96

1 Answers1

3

Here is the spec if you really want to implement it...

https://docs.oracle.com/javase/8/docs/platform/serialization/spec/protocol.html

I'd recommend not using java's object serialization.

JSON is the langue de jour for this sort of thing.

Python has the json package Java has Jackson's ObjectMapper for reading json.

If you really want to get fancy, you could have the first level of the serialization to be the name of the bean property and reflectively set the value:

Using reflection to set an object property

  • I understand this can be easily achieved with JSON (should have mentioned that in the question), but underfortunately, I can't change server side code due to some limitation. – jagamot May 17 '18 at 11:30