Java Server Q&A

Started by
27 comments, last by Kylotan 6 years, 8 months ago

Hi guys,

So I made this thread to deal with my server problems! 

First thing's first, in this guy's server code he has the following

 

  1. do{//Start a do while loop while run is true
  2. Socket newConnection = server.accept();//Check if we have a connection, if we do continue otherwise try again
  3. String name = "guest"+ply;//Select an unique name for this player
  4. Player p = new Player(name, newConnection);//Create a new Player instance and set the socket to it
  5. System.out.println("New Player Connected from IP: "+newConnection.getInetAddress()+" and was assigned the name "+name);//Display the message that we got a new player
  6. ep.execute(p);//Assign the player instance a thread
  7. players.put(name, p);//Add the player instance to the player HashMap
  8. }while (run);

 

At line 2 he commented, check if we have a connection and if we do continue otherwise try again..

I don't see an if statement, so how is he preventing line 3 and up from running if there isn't a connection ?

When I look up the .accept method it says this 

  • Listens for a connection to be made to this socket and accepts it. The method blocks until a connection is made.
when it says block does that mean the code wont read past line 2 until a connection is made ? 
 
Advertisement

That's hard to say without knowing what type the `server` object is. My best two guesses are either

  1. The `accept()` method keeps checking for a connection and returns when it gets it. (You can probably check that easily looking at the method implementation)
  2. The comment is wrong.

if its using a ServerSocket in Java, the .accept() method blocks until it receives a connection, so until it actually has a connection it will just block further execution of code.. or thats how it should work.. so doesnt need an if statement

Thanks, yes it is using ServerSocket, that makes sense..

I'm not using threads at the moment, because I don't want to complicate the code too soon, first getting a feel for how running a server works.

At line 4 I'm creating an instance of the class Player, what I'm wondering is at what point does the code within that instance run ? will the new Player instance's code run before line 5 runs ? 

Well line 4 creates a new Player and passes in two parameters, so in the Player class will obviously be a matching constructor, anything in that constructor will happen before line 5 happens yes.

You should read constructor method. This is based on these issues. 

JAVA Course at CETPA 

So the constructor for the new player object is run immediately before line 5, but what about the rest of the code in the player object ? is that run immediately or will it run after all the code from the main method first ? 

 

script 1:

lots of code, also creates a new object player with more code that follows

 

script 2:

player object has code and runs..

 

does script 1 finish first before script 2 from player object is run ? or does script 1 run then create object player then run script 2s code and once finished it continues with script 1.

 

In both cases it's been determined that the constructor for object player will run

What code is inside the Player class exactly?

When you create a new player, its constructor will get called, but other than that no code will be executed it until that code is called.

Since the while loop on the server doesnt seem to be call any code from the Player in your example then no code inside of that class other than the constructor should fire.

So no methods within the player class will run unless I call those methods from another class ? or call them in the constructor ? That kind of makes sense. Ill have to see where the player class is being used. 

 

Server Class:


package mypackage;

//Import area
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Server {

    private static ServerSocket server; // Define the server socket
    private static boolean run = true; //Continuously run server loop Switch
    private static HashMap<String, Player> players = new HashMap <String, Player>();// create an array list to store all players
    
    //use threads
    public static int player_count = 0; //holds player count
    
    public static void main(String[] args){
    
        try {
            System.out.println("Starting Server...");
            server = new ServerSocket(1234,10); //New server socket object 
            System.out.println("Server started on port: " + Integer.toString(server.getLocalPort()));
            
            do{
                Socket newConnection = server.accept();
                String name = "Guest"+player_count;//Gives each new player a unique name(change later)
                Player p = new Player(name,newConnection); //Create a new Player instance and set the socket to it
                System.out.println("New player connected: " + name);
                players.put(name,p); //add the new player instance to the player HashMap
                
            }while (run);
            
        } catch (IOException e) {}
        
        
    
    }
    
    
}

 

 

Player class:


package mypackage;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.SocketTimeoutException;

public class Player {

    private DataOutputStream output;//define a data output that we will later use to send messages to the client
    private DataInputStream input; //define a data input stream that we will later us to read messages from the client;
    private Socket socket;// define a socket
    private boolean alive = true; //define a boolean to keep the player class running
    private String name; //define a string that will hold the player name
    
    public Player(String nm, Socket sck) //constructor or method ?
    {
        socket =sck; //set the received socket to the player class
        name = nm;// set the player name
        
        
        try {
            socket.setSoTimeout(30000);//Set the socket timeout to 30 seconds
            output = new DataOutputStream(socket.getOutputStream()); //get the data output stream and set it to output
            output.flush();//flush away all the bytes on the data output stream
            input = new DataInputStream(socket.getInputStream()); //get the data input stream and set it to input
            
        } catch(IOException e){}
    }

    
    
    public void run()
    {
        do
        { //start a do loop while alive is true
            checkForMessages();//check for messages
        }
        while (alive);
    }        
        
    
    private void checkForMessages()
    {
        byte received;
        
        try
        {
            received = input.readByte();//read the header from the message
        }catch(IOException ex){alive = false; return;}
        
        
        if (received == -34) 
        { //header start ?
            
            try {
                    input.skipBytes(11); //ignore the header
                    received = input.readByte(); //message ID
                    switch (received)
                    {
                        case 0:
                        break;
                    }
                }catch (SocketTimeoutException ex)
            
            {
                    
                    //if we get a socket timoue display it and free the player's instance
                    System.out.println("Disconnected "+name+ "due to timeout.");
                    alive =false;
            }catch (IOException ex){
                ex.printStackTrace();
            }
        }
    }
    

}

 

 

This is all the server code, Is the run method being called anywhere ? I don't see it being called.. from my understanding or from what you've said the methods must be called somewhere before it is run. 

Well, from what I can see it doesnt look like the player run code is ever being called, so it looks like the program gets a Player, add it to a list and thats about it, though if you want to double check if it ever gets called you can just put a break point on the run() function in the player class. Not sure what IDE youre using though you should be able to just stick break points in.

This topic is closed to new replies.

Advertisement