Question with sending an object through java sockets

So, I was working on a Tic-Tac-Toe 2 player game in java that uses sockets. All socket stuff works, and I successfully send data between two clients and the server.

I have the following classes: Requester, Provider and TBoard (which extends Serializable).

In the Requester class (client), I create a TBoard ( TBoard board = new TBoard()) object .

Then I send this object through the socket to my two clients via the output stream.

The error I get is on the client side, and this is: Exception in thread "main" java.lang.ClassCastException: java.lang.String

What happens to:

 board = (TBoard) in.readObject(); in:

 do {
    try {
       board = (TBoard) in.readObject();
       System.out.println(board.print_board());
    } catch (ClassNotFoundException classNot) {
       System.err.println("data received in unknown format");
    }

My print_board () method in the TBoard class is designed to return a 2d array, but right now (simplification), I have a method that returns the string "Hello" ...

- , ? , , , , ...

!


UPDATE:

( ) Provider (server):

 // 1. creating a server socket
 providerSocket = new ServerSocket(20092);

 // 2. Wait for connection
 System.out.println("Waiting for connection...");

 connection1 = providerSocket.accept();
 System.out.println("Connection received from Player 1 "    + 

 connection1.getInetAddress().getHostName());
 connection2 = providerSocket.accept();
 System.out.println("Connection received from Player 2 " + connection2.getInetAddress().getHostName());

 // 3. get Input and Output streams
 out = new ObjectOutputStream(connection1.getOutputStream());

 out2 = new ObjectOutputStream(connection2.getOutputStream());

 in = new ObjectInputStream(connection1.getInputStream());
 out.writeObject("Player 1 has been connected successfully.");
 in2 = new ObjectInputStream(connection2.getInputStream());
 out2.writeObject("Player 2 has been connected successfully.");

 out.flush();
 out2.flush();

 out.writeObject(board);
 out2.writeObject(board);

String (). , . reset() , IllegalCastException...

+3
3

IIRC, , Exception, , , , , :

board = (TBoard) in.readObject();

String TBoard, .

Edit: , . . , . flush() - , , , .

+3

, , ( ) , in.readObject(). :

    Object o = in.readObject();
    System.out.println("Object of class " + o.getClass().getName() + " is " + o);
+2

. , ObjectOutputStream (, , ), , - , . ObjectOutputStream , reset .

:

1) make sure you are flush () and close () the sockets at the appropriate time

2) try calling reset () after sending each object.

3) make sure that you send and receive the same type of object, just in case.

Good luck.

+1
source

Source: https://habr.com/ru/post/1718357/


All Articles