Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to send an OBJECT over TCP in java?
    primarykey
    data
    text
    <p>I'm writing a program to send an <strong>object</strong> from one class to another class. Here is a short sample example of my program to represent the problem. As you can see the object to send from server to client is Student class <strong>which has been defined separately in each class(Server/Client).</strong> I have examined this code by sending an ArrayList which works fine but when it comes to a class type which defined by myself i'm receiving this error:</p> <pre><code>Exception in thread "main" java.lang.ClassCastException: ServerSide$1Student cannot be cast to ClientSide$1Student at ClientSide.main(ClientSide.java:29) </code></pre> <p>Here is the code for Server side:</p> <pre><code>import java.io.*; import java.net.*; public class ServerSide { public static void main(String[] args) { class Student implements Serializable { int id; public Student(int num){id=num;} public void setID(int num){id=num;} public void Print(){System.out.println("id = " + id);} } try { Student a = new Student(3); ServerSocket myServerSocket = new ServerSocket(9999); Socket skt = myServerSocket.accept(); try { ObjectOutputStream objectOutput = new ObjectOutputStream(skt.getOutputStream()); objectOutput.writeObject(a); } catch (IOException e) { e.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } } } </code></pre> <p>And for the client side is: </p> <pre><code>import java.io.*; import java.net.Socket; import java.net.UnknownHostException; public class ClientSide { public static void main(String[] args) { class Student implements Serializable { int id; public Student(int num){id=num;} public void setID(int num){id=num;} public void Print(){System.out.println("id = " + id);} } try { Socket socket = new Socket("10.1.1.2",9999); try { ObjectInputStream objectInput = new ObjectInputStream(socket.getInputStream()); try { Object object =(Student) objectInput.readObject(); Student tmp = (Student) object; tmp.Print(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } </code></pre> <p><strong>Edit:</strong></p> <p><strong>I moved them to same file and added serialise ID. It works fine.</strong></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload