Exception in Client-Server connection - JavaFX Battleship Game

  • (2 Pages)
  • +
  • 1
  • 2

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

#16 prubic  Icon 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 03 January 2018 - 06:12 AM

I think so. I realized it would be easier for me to just send the coordinates of the ships in GridPane over Server to another player instead of sending the entire JavaFX GridPane which requires the Server to have a Toolkit initialized.
Was This Post Helpful? 0
  • +
  • -

#17 prubic  Icon 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 08 January 2018 - 04:29 PM

When I added sending of the coordinates, everything works well except I get another exception for null pointer when I click on the button on opponent's board where I have to guess where the ship is:

Current guess: null
sij 09, 2018 12:22:32 AM com.prubic.view.GameBoard guess
SEVERE: null
java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at java.net.Socket.connect(Socket.java:538)
at java.net.Socket.<init>(Socket.java:434)
at java.net.Socket.<init>(Socket.java:211)
at com.prubic.server.Client.connectToServer(Client.java:25)
at com.prubic.view.GameBoard.guess(GameBoard.java:57)
at com.prubic.view.GameBoard.lambda$new$0(GameBoard.java:45)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Node.fireEvent(Node.java:8413)
at javafx.scene.control.Button.fire(Button.java:185)
at com.sun.javafx.scene.control.behavior.Buttonbehavior.mouseReleased(Buttonbehavior.java:182)
at com.sun.javafx.scene.control.skin.behaviorSkinBase$1.handle(behaviorSkinBase.java:96)
at com.sun.javafx.scene.control.skin.behaviorSkinBase$1.handle(behaviorSkinBase.java:89)
at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Scene$MouseHandler.process(Scene.java:3757)
at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485)
at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:381)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$354(GlassViewEventHandler.java:417)
at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:416)
at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
at com.sun.glass.ui.View.notifyMouse(View.java:937)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
at java.lang.Thread.run(Thread.java:748)

Here is my code:

public class GameBoard extends GridPane implements Serializable {

    private Cell[][] board;
    private Ship hitShip;
    private Player player;
    public Coordinates guessCoordinates;
    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].setOnAction(e -> guess(e));
                this.add(board[row][col], col, row);
            }
        }       
    }

    public void guess(ActionEvent e) {
        
        Client client = new Client();
        
        try {
            System.out.println("Current guess: " + this.guessCoordinates);
            client.connectToServer(this.guessCoordinates);
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        Cell guess = (Cell) e.getSource();
        guessCoordinates = getGuessCoordinates(guess);
        
        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());
                
                if (hitShip.getShipOwner().getShips().isEmpty()) {
                    Main.gameOver();
                }
                
            }
            
            removeListeners();
            guessedCell = guess;
            
        } else {
            guess.setStyle("-fx-background: #000000");
            removeListeners();
            Main.shipStatus.setTextFill(Color.YELLOW);
            Main.shipStatus.setText("Miss!");
        }
        
        Main.rotateBtn.setVisible(true);
    }

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

    private void addClickListeners() {
        
        for (int col = 0; col < 10; col++) {
            for (int row = 0; row < 10; row++) {
                board[row][col].setOnAction(e -> guess(e));
            }
        }
    }

    private Coordinates getGuessCoordinates(Cell guess) {
        return new Coordinates(guess.getRow(), guess.getCol());
    }



public class Client {
    
    private String responseFromServer;
    
    public void connectToServer(Coordinates guessCoordinates) throws IOException {
                
        try (Socket s = new Socket("localhost", 1234)) {
            
            ObjectOutputStream clientOutputStream = new ObjectOutputStream(s.getOutputStream());
            BufferedReader socketReader = new BufferedReader(new InputStreamReader(s.getInputStream()));
                       
            System.out.println("Connected to server: " + s);
            
            clientOutputStream.writeObject(guessCoordinates);
            clientOutputStream.flush();
            
            System.out.println("Client sending coordinates: (" + guessCoordinates.getX() + "," + guessCoordinates.getY() + ")");
            
            clientOutputStream.close();
            
            System.out.println("Response from server: " + socketReader.readLine());
                        
        }
        
        
    }
}



public class Server {

    private static final Logger LOG = Logger.getLogger(Server.class.getName());
    
    public static void main(String[] args) {
        
        Coordinates guessCoordinates = null;
        
        try {
            
            ServerSocket s = new ServerSocket(1234);
            
            LOG.info("Server waiting for client...");
            
            Socket clientSocket = s.accept();
            LOG.log(Level.INFO, "Server accepted client: {0}", clientSocket);
            
            ObjectInputStream serverInputStream = new ObjectInputStream(clientSocket.getInputStream());
        
            guessCoordinates = (Coordinates) serverInputStream.readObject();
        
            System.out.println("Server reading coordinates: (" + guessCoordinates.getX() + "," + guessCoordinates.getY() + ")");   
        
            serverInputStream.close();
            
        } catch (IOException | ClassNotFoundException ex) {
            Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
        }              
    }   
}




Should I change something in the following code where I somehow bind the ship to the cells on designed board when the ship is placed? Maybe that is why I get null when I click on the cell of the opponent board. There is probably nothing on that cell as it doesn't save ships that are placed there.


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
  • +
  • -

#18 g00se  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 3536
  • View blog
  • Posts: 16,028
  • Joined: 20-September 08

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

Posted 08 January 2018 - 05:13 PM

Probably the other end is not listening, so you can't connect
Was This Post Helpful? 0
  • +
  • -

#19 prubic  Icon 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 09 January 2018 - 04:22 AM

View Postg00se, on 08 January 2018 - 05:13 PM, said:

Probably the other end is not listening, so you can't connect


So should I have something in my Client class that has to wait for given coordinates or listen if the button is clicked and where it is clicked?
Was This Post Helpful? 0
  • +
  • -

#20 g00se  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 3536
  • View blog
  • Posts: 16,028
  • Joined: 20-September 08

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

Posted 09 January 2018 - 04:52 AM

You try to connect your client to the server in Client.connectToServer. It is failing - probably because the other end is not listening
Was This Post Helpful? 0
  • +
  • -

#21 prubic  Icon 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 11 January 2018 - 07:43 AM

View Postg00se, on 09 January 2018 - 04:52 AM, said:

You try to connect your client to the server in Client.connectToServer. It is failing - probably because the other end is not listening


Thank you, I got it to work!
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2