Exception in Client-Server connection - JavaFX Battleship Game

  • (2 Pages)
  • +
  • 1
  • 2

20 Replies - 1438 Views - Last Post: 11 January 2018 - 07:43 AM Rate Topic: -----

#1 prubic   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 20
  • Joined: 10-November 15

Exception in Client-Server connection - JavaFX Battleship Game

Posted 21 December 2017 - 06:43 AM

I am working on client and server communication for Battleship game in Java and I got this exception which I don't know how to fix and how to make it so that another player can connect to that server. I am also trying to send the GameBoard object to another player so that he can see when the opponent ship is hit.

pro 21, 2017 2:34:31 PM com.prubic.server.Server main
INFO: Server waiting for client...
pro 21, 2017 2:34:31 PM com.prubic.server.ClientProcessor run
INFO: Object to process client: Socket[addr=/127.0.0.1,port=50127,localport=1234]
Exception in thread "Thread-1" java.lang.ExceptionInInitializerError
at java.io.ObjectStreamClass.hasStaticInitializer(Native Method)...
at com.prubic.server.ClientProcessor.run(ClientProcessor.java:47)
Caused by: java.lang.IllegalStateException: Toolkit not initialized
at com.sun.javafx.application.PlatformImpl.runLater(PlatformImpl.java:273)
at com.sun.javafx.application.PlatformImpl.runLater(PlatformImpl.java:268)

My code:

public class ClientProcessor extends Thread {

    private static final Logger LOG = Logger.getLogger(ClientProcessor.class.getName());
    
    private final Socket clientSocket;
    private final BufferedReader reader;
    private final PrintWriter printWriter;
    
    
    public ClientProcessor(Socket clientSocket) throws IOException {       
        this.clientSocket = clientSocket;
        reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        printWriter = new PrintWriter(clientSocket.getOutputStream());
        
        LOG.log(Level.INFO, "Created client processor for: {0}", clientSocket);       
    }
    
    @Override
    public void run() {
        
        LOG.log(Level.INFO, "Object to process client: {0}", clientSocket);        
        
        try {
            
            ObjectInputStream inputStream = new ObjectInputStream(clientSocket.getInputStream());
            GameBoard gameBoard = (GameBoard) inputStream.readObject();           
            
        } catch (IOException ex) {
            LOG.warning(ex.getMessage());
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(ClientProcessor.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            close(clientSocket);
        }
    }

    private void close(Socket clientSocket) {
        
        try {
            
            clientSocket.close();
            
        } catch (IOException ioEx) {
            LOG.log(Level.WARNING, ioEx.getMessage(), ioEx);
        }
    }
    
}



public class Server {

    private static final Logger LOG = Logger.getLogger(Server.class.getName());
    
    public static void main(String[] args) throws IOException {
        
        ServerSocket s = new ServerSocket(1234);
        
        while (true) {   
            
            LOG.info("Server waiting for client...");
            
            Socket clientSocket = s.accept();
            LOG.log(Level.INFO, "Server accepted client: {0}", clientSocket);
            
            new ClientProcessor(clientSocket).start();           
        }       
    }
    
}



public class Client {
    
    private String responseFromServer;
    
    public String connectToServer(GameBoard playerBoard) throws IOException {
                
        try (Socket s = new Socket("localhost", 1234)) {
            
            ObjectOutputStream outputStream = new ObjectOutputStream(s.getOutputStream());
            BufferedReader socketReader = new BufferedReader(new InputStreamReader(System.in));
            
            System.out.println("Connected to server: " + s);
            System.out.println("Object to be written = " + playerBoard);
            outputStream.writeObject(playerBoard);
            outputStream.flush();
            
            responseFromServer = socketReader.readLine();
        }
        
        return responseFromServer;
    }
}



Is This A Good Question/Topic? 0
  • +

Replies To: Exception in Client-Server connection - JavaFX Battleship Game

#2 g00se   User is offline

  • D.I.C Lover
  • member icon

Reputation: 3550
  • View blog
  • Posts: 16,190
  • Joined: 20-September 08

Re: Exception in Client-Server connection - JavaFX Battleship Game

Posted 21 December 2017 - 07:28 AM

GameBoard should have public ctor GameBoard(). Does it?
Was This Post Helpful? 0
  • +
  • -

#3 prubic   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 20
  • Joined: 10-November 15

Re: Exception in Client-Server connection - JavaFX Battleship Game

Posted 21 December 2017 - 08:23 AM

View Postg00se, on 21 December 2017 - 07:28 AM, said:

GameBoard should have public ctor GameBoard(). Does it?


GameBoard has constructor that takes in two parameters DesignedBoard and a Player. Here is the code:
public class GameBoard extends GridPane implements Serializable {

    private static Object FSCONTEXT = "com.sun.jndi.fscontext.RefFSContextFactory";
    private static Object URL = "file:C:/";
    private static String FILENAME = "shipTracker.txt";
    private static CharSequence SEPARATOR = "|";

    private Cell[][] board;
    private Ship hitShip;
    private Player player;
    public Cell guessedCell;

    public GameBoard(DesignedBoard placementBoard, Player player) {
        super();
        this.board = placementBoard.getBoard();
        this.player = player;
        
        for (int col = 0; col < 10; col++) {
            for (int row = 0; row < 10; row++) {
                //board[row][col].setFill(Color.TRANSPARENT);
                board[row][col].setOnMouseClicked(e -> guess(e));
                this.add(board[row][col], col, row);
            }
        }       
    }

    public void guess(MouseEvent e) {
        
        Cell guess = (Cell) e.getSource();
        
        if (guess.isShip()) {
            
            guess.setStyle("-fx-background: #FF0000");
            hitShip = guess.getShip();
            hitShip.hit(guess);
            
            Main.shipStatus.setTextFill(Color.BEIGE);
            Main.shipStatus.setText("Opponent's ship is hit!");
            Main.bottomBox.setStyle("-fx-background-color: linear-gradient(to top right, red, crimson, black);");
            
            if (!hitShip.isAfloat()) {
                
                Main.shipStatus.setText("Ship is sunk!");
                hitShip.getShipOwner().sinkShip(hitShip);
                Main.emptyLabel.setText("Opponent ships remaining: " + hitShip.getShipOwner().getShips().size());
                
                try {
                    writeToFile(hitShip);
                } catch (NamingException ex) {
                    Logger.getLogger(GameBoard.class.getName()).log(Level.SEVERE, null, ex);
                }
                
                if (hitShip.getShipOwner().getShips().isEmpty()) {
                    Main.gameOver();
                }
                
            }
            
            removeListeners();
            
        } else {
            //guess.setFill(Color.YELLOW);
            removeListeners();
            Main.shipStatus.setTextFill(Color.YELLOW);
            Main.shipStatus.setText("Miss!");
        }
        
        Main.rotateBtn.setVisible(true);
        guessedCell = guess;
    }

    private void removeListeners() {
        
        for (int col = 0; col < 10; col++) {
            for (int row = 0; row < 10; row++) {
                board[row][col].setOnMouseClicked(null);
            }
        }       
    }
    
    public void endTurn() {
        Main.incrementTurn();
        addClickListeners();
        Main.shipStatus.setText("");
        Main.continueGame();
    }

    private void addClickListeners() {
        
        for (int col = 0; col < 10; col++) {
            for (int row = 0; row < 10; row++) {
                board[row][col].setOnMouseClicked(e -> guess(e));
            }
        }
    }
    
    public static void writeToFile(Ship hitShip) throws NamingException {
        
        Hashtable htable = new Hashtable();
        
        htable.put(Context.INITIAL_CONTEXT_FACTORY, FSCONTEXT);
        htable.put(Context.PROVIDER_URL, URL);
        
        Context context = new InitialContext(htable);
        File file = (File) context.lookup(FILENAME);
        
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
            
            writer.append(hitShip.getShipOwner().toString());
            writer.append(SEPARATOR);
            writer.append((char) hitShip.getShipOwner().getShips().size());
            
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        
    }


Was This Post Helpful? 0
  • +
  • -

#4 g00se   User is offline

  • D.I.C Lover
  • member icon

Reputation: 3550
  • View blog
  • Posts: 16,190
  • Joined: 20-September 08

Re: Exception in Client-Server connection - JavaFX Battleship Game

Posted 21 December 2017 - 08:36 AM

You need an empty one as well for deserialization to happen
Was This Post Helpful? 0
  • +
  • -

#5 prubic   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 20
  • Joined: 10-November 15

Re: Exception in Client-Server connection - JavaFX Battleship Game

Posted 22 December 2017 - 03:40 PM

View Postg00se, on 21 December 2017 - 08:36 AM, said:

You need an empty one as well for deserialization to happen


Ok, I added an empty one but the exception still comes up. Should I add code to Server class where I also get the input as GameBoard?
Was This Post Helpful? 0
  • +
  • -

#6 g00se   User is offline

  • D.I.C Lover
  • member icon

Reputation: 3550
  • View blog
  • Posts: 16,190
  • Joined: 20-September 08

Re: Exception in Client-Server connection - JavaFX Battleship Game

Posted 22 December 2017 - 03:52 PM

Anything that deals with GameBoard has to have the correct class file with an empty ctor
Was This Post Helpful? 0
  • +
  • -

#7 prubic   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 20
  • Joined: 10-November 15

Re: Exception in Client-Server connection - JavaFX Battleship Game

Posted 22 December 2017 - 04:13 PM

Ok, I added an empty constructor to DesignedBoard and I already have it defined in Player class:

public class Player implements Serializable {
    
    private final DesignedBoard designedBoard;
    private final GameBoard gameBoard = null;
    private ArrayList<Ship> playerShips;
    
    public Player() {
        this.designedBoard = new DesignedBoard(this);
        this.playerShips = new ArrayList<>();
    }

    public DesignedBoard getBoard() {
        return designedBoard;
    }

    public ArrayList<Ship> getShips() {
        return playerShips;
    }
    
    public void addShip(Ship ship) {
        playerShips.add(ship);
    }
    
    public void sinkShip(Ship ship) {
        this.playerShips.remove(ship);
    }
    
    
}



public class DesignedBoard extends GridPane implements Serializable {
    
    private Cell cell;
    private Cell[][] board = new Cell[10][10];
    
    private boolean rotated = false;
    private Player player;

    public DesignedBoard() {
    }
    
    public DesignedBoard(Player player) {
        
        super();
        this.setGridLinesVisible(true);
        this.player = player;

        
        for (int col = 0; col < 10; col++) {
            for (int row = 0; row < 10; row++) {
                board[row][col] = new Cell(row, col);
                this.add(board[row][col], col, row);
            }
        }
        
    }
    
    public Cell[][] getBoard() {
        return board;
    }

    public boolean isRotated() {
        return rotated;
    }

    public void setRotated(boolean rotated) {
        this.rotated = rotated;
    }
    
    public void placeShip(ArrayList<Integer> shipSizes) {    
        
        for (Cell[] cell : board) {
            for (Cell c : cell) {
               c.setOnMouseClicked(e -> createShip(e, shipSizes));
            }
        }
    }

    private void createShip(MouseEvent e, ArrayList<Integer> shipSizes) {
        	
	int shipSize = shipSizes.get(0);
        
	Cell currentCell = (Cell) e.getSource();
	int col = currentCell.getCol();
	int row = currentCell.getRow();
		
	int maxTile = board[0].length - shipSize;
                
	ArrayList<Cell> ship = new ArrayList<>();
				
	if (!rotated){
	
            if (col > maxTile) {
		
                for (int i = maxTile; i < board[0].length; i++) {
			ship.add(board[row][i]);
                }
                
            } else {
                
                for (int i = col; i < col + shipSize; i++) {
                    ship.add(board[row][i]);
                }
            }
            
        } else {
            
            if (row > maxTile) {
                
                for (int i = maxTile; i < board[0].length; i++) {
                    ship.add(board[i][col]);
                }
                
            } else {
                
                for (int i = row; i < row + shipSize; i++) {
                    ship.add(board[i][col]);
                }
            }
        }
        
        try {
            
            player.addShip(new Ship(ship, player));
            
            for (Cell c : ship) {
                c.setStyle("-fx-background-color: #4265f4; -fx-border-color: #1d1863; -fx-border-width: 2px");
            }
            
            shipSizes.remove(0);
            
            Main.placeShips(shipSizes);
            
        } catch (ShipAlreadyCreatedException ex) {
            return;
        }
    }
}


Was This Post Helpful? 0
  • +
  • -

#8 g00se   User is offline

  • D.I.C Lover
  • member icon

Reputation: 3550
  • View blog
  • Posts: 16,190
  • Joined: 20-September 08

Re: Exception in Client-Server connection - JavaFX Battleship Game

Posted 23 December 2017 - 03:36 AM

And GameBoard?
Was This Post Helpful? 0
  • +
  • -

#9 prubic   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 20
  • Joined: 10-November 15

Re: Exception in Client-Server connection - JavaFX Battleship Game

Posted 23 December 2017 - 07:34 AM

View Postg00se, on 23 December 2017 - 03:36 AM, said:

And GameBoard?


Here is GameBoard:

public class GameBoard extends GridPane implements Serializable {

    private static Object FSCONTEXT = "com.sun.jndi.fscontext.RefFSContextFactory";
    private static Object URL = "file:C:/";
    private static String FILENAME = "shipTracker.txt";
    private static CharSequence SEPARATOR = "|";

    private Cell[][] board;
    private Ship hitShip;
    private Player player;
    public Cell guessedCell;

    public GameBoard() {
    }

    public GameBoard(DesignedBoard placementBoard, Player player) {
        super();
        this.board = placementBoard.getBoard();
        this.player = player;
        
        for (int col = 0; col < 10; col++) {
            for (int row = 0; row < 10; row++) {
                //board[row][col].setFill(Color.TRANSPARENT);
                board[row][col].setOnMouseClicked(e -> guess(e));
                this.add(board[row][col], col, row);
            }
        }       
    }

    public void guess(MouseEvent e) {
        
        Cell guess = (Cell) e.getSource();
        
        if (guess.isShip()) {
            
            guess.setStyle("-fx-background: #FF0000");
            hitShip = guess.getShip();
            hitShip.hit(guess);
            
            Main.shipStatus.setTextFill(Color.BEIGE);
            Main.shipStatus.setText("Opponent's ship is hit!");
            Main.bottomBox.setStyle("-fx-background-color: linear-gradient(to top right, red, crimson, black);");
            
            if (!hitShip.isAfloat()) {
                
                Main.shipStatus.setText("Ship is sunk!");
                hitShip.getShipOwner().sinkShip(hitShip);
                Main.emptyLabel.setText("Opponent ships remaining: " + hitShip.getShipOwner().getShips().size());
                
                try {
                    writeToFile(hitShip);
                } catch (NamingException ex) {
                    Logger.getLogger(GameBoard.class.getName()).log(Level.SEVERE, null, ex);
                }
                
                if (hitShip.getShipOwner().getShips().isEmpty()) {
                    Main.gameOver();
                }
                
            }
            
            removeListeners();
            
        } else {
            //guess.setFill(Color.YELLOW);
            removeListeners();
            Main.shipStatus.setTextFill(Color.YELLOW);
            Main.shipStatus.setText("Miss!");
        }
        
        Main.rotateBtn.setVisible(true);
        guessedCell = guess;
    }

    private void removeListeners() {
        
        for (int col = 0; col < 10; col++) {
            for (int row = 0; row < 10; row++) {
                board[row][col].setOnMouseClicked(null);
            }
        }       
    }
    
    public void endTurn() {
        Main.incrementTurn();
        addClickListeners();
        Main.shipStatus.setText("");
        Main.continueGame();
    }

    private void addClickListeners() {
        
        for (int col = 0; col < 10; col++) {
            for (int row = 0; row < 10; row++) {
                board[row][col].setOnMouseClicked(e -> guess(e));
            }
        }
    }
    
    public static void writeToFile(Ship hitShip) throws NamingException {
        
        Hashtable htable = new Hashtable();
        
        htable.put(Context.INITIAL_CONTEXT_FACTORY, FSCONTEXT);
        htable.put(Context.PROVIDER_URL, URL);
        
        Context context = new InitialContext(htable);
        File file = (File) context.lookup(FILENAME);
        
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
            
            writer.append(hitShip.getShipOwner().toString());
            writer.append(SEPARATOR);
            writer.append((char) hitShip.getShipOwner().getShips().size());
            
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        
    }
}



Was This Post Helpful? 0
  • +
  • -

#10 g00se   User is offline

  • D.I.C Lover
  • member icon

Reputation: 3550
  • View blog
  • Posts: 16,190
  • Joined: 20-September 08

Re: Exception in Client-Server connection - JavaFX Battleship Game

Posted 23 December 2017 - 10:20 AM

OK, so you need to make sure you rebuild all with that code
Was This Post Helpful? 0
  • +
  • -

#11 prubic   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 20
  • Joined: 10-November 15

Re: Exception in Client-Server connection - JavaFX Battleship Game

Posted 23 December 2017 - 10:51 AM

Ok, I did the rebuild of the code and tried to run the server and the program again. I get more information about client connecting to server now, but then I get the same exception:

pro 23, 2017 6:48:29 PM com.prubic.server.Server main
INFO: Server waiting for client...
pro 23, 2017 6:48:32 PM com.prubic.server.Server main
INFO: Server accepted client: Socket[addr=/127.0.0.1,port=50596,localport=1234]
pro 23, 2017 6:48:32 PM com.prubic.server.ClientProcessor <init>
INFO: Created client processor for: Socket[addr=/127.0.0.1,port=50596,localport=1234]
pro 23, 2017 6:48:32 PM com.prubic.server.Server main
INFO: Server waiting for client...
pro 23, 2017 6:48:32 PM com.prubic.server.ClientProcessor run
INFO: Object to process client: Socket[addr=/127.0.0.1,port=50596,localport=1234]
Exception in thread "Thread-1" java.lang.ExceptionInInitializerError...
Was This Post Helpful? 0
  • +
  • -

#12 g00se   User is offline

  • D.I.C Lover
  • member icon

Reputation: 3550
  • View blog
  • Posts: 16,190
  • Joined: 20-September 08

Re: Exception in Client-Server connection - JavaFX Battleship Game

Posted 24 December 2017 - 03:42 AM

Need to see all of that
Was This Post Helpful? 0
  • +
  • -

#13 prubic   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 20
  • Joined: 10-November 15

Re: Exception in Client-Server connection - JavaFX Battleship Game

Posted 24 December 2017 - 04:48 PM

View Postg00se, on 24 December 2017 - 03:42 AM, said:

Need to see all of that


This is from Server main:

pro 25, 2017 12:46:59 AM com.prubic.server.Server main
INFO: Server waiting for client...
pro 25, 2017 12:47:05 AM com.prubic.server.Server main
INFO: Server accepted client: Socket[addr=/127.0.0.1,port=51929,localport=1234]
pro 25, 2017 12:47:05 AM com.prubic.server.ClientProcessor <init>
INFO: Created client processor for: Socket[addr=/127.0.0.1,port=51929,localport=1234]
pro 25, 2017 12:47:05 AM com.prubic.server.Server main
INFO: Server waiting for client...
pro 25, 2017 12:47:05 AM com.prubic.server.ClientProcessor run
INFO: Object to process client: Socket[addr=/127.0.0.1,port=51929,localport=1234]
Exception in thread "Thread-1" java.lang.ExceptionInInitializerError
at java.io.ObjectStreamClass.hasStaticInitializer(Native Method)
at java.io.ObjectStreamClass.computeDefaultSUID(ObjectStreamClass.java:1787)
at java.io.ObjectStreamClass.access$100(ObjectStreamClass.java:72)
at java.io.ObjectStreamClass$1.run(ObjectStreamClass.java:253)
at java.io.ObjectStreamClass$1.run(ObjectStreamClass.java:251)
at java.security.AccessController.doPrivileged(Native Method)
at java.io.ObjectStreamClass.getSerialVersionUID(ObjectStreamClass.java:250)
at java.io.ObjectStreamClass.initNonProxy(ObjectStreamClass.java:611)
at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1843)
at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1713)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2000)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1535)
at java.io.ObjectInputStream.readArray(ObjectInputStream.java:1933)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1529)
at java.io.ObjectInputStream.readArray(ObjectInputStream.java:1933)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1529)
at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:2245)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:2169)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2027)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1535)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:422)
at com.prubic.server.ClientProcessor.run(ClientProcessor.java:47)
Caused by: java.lang.IllegalStateException: Toolkit not initialized
at com.sun.javafx.application.PlatformImpl.runLater(PlatformImpl.java:273)
at com.sun.javafx.application.PlatformImpl.runLater(PlatformImpl.java:268)
at com.sun.javafx.application.PlatformImpl.setPlatformUserAgentStylesheet(PlatformImpl.java:550)
at com.sun.javafx.application.PlatformImpl.setDefaultPlatformUserAgentStylesheet(PlatformImpl.java:512)
at javafx.scene.control.Control.<clinit>(Control.java:87)
... 22 more

And this is from project Main:

Connected to server: Socket[addr=localhost/127.0.0.1,port=1234,localport=51929]
Object to be written = Grid hgap=0.0, vgap=0.0, alignment=TOP_LEFT
Was This Post Helpful? 0
  • +
  • -

#14 prubic   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 20
  • Joined: 10-November 15

Re: Exception in Client-Server connection - JavaFX Battleship Game

Posted 28 December 2017 - 04:06 AM

Should I implement Platform.runLater when I start my JavaFX application? And I also changed my ChatServer port to be different than port for this Server but I still get the same exception.
Was This Post Helpful? 0
  • +
  • -

#15 g00se   User is offline

  • D.I.C Lover
  • member icon

Reputation: 3550
  • View blog
  • Posts: 16,190
  • Joined: 20-September 08

Re: Exception in Client-Server connection - JavaFX Battleship Game

Posted 28 December 2017 - 06:04 AM

You shouldn't be trying to trying to create something that requires windowing before windowing is possible. Do you think that's what's happening?
Was This Post Helpful? 1
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2