• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Xer0botXer0

Java Server Q&A

16 posts in this topic

Posted (edited)

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 ? 
 
Edited by Xer0botXer0
0

Share this post


Link to post
Share on other sites

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.
1

Share this post


Link to post
Share on other sites

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

1

Share this post


Link to post
Share on other sites

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 ? 

0

Share this post


Link to post
Share on other sites

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.

1

Share this post


Link to post
Share on other sites

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

0

Share this post


Link to post
Share on other sites

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.

0

Share this post


Link to post
Share on other sites

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. 

0

Share this post


Link to post
Share on other sites

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.

0

Share this post


Link to post
Share on other sites

Yeap I tested it with println, it wasn't calling those methods. Eventually I added run() method to the player constructor.

Weird how the tutorial excluded that.

 

The guy who wrote the tutorial also failed to explain a bit and he was using deprecated information.

Going to look for a new one.

 

So I've got a new question, if I want to send/receive data through a buffer over the network which classes/methods would I need, I'm not sure which they're called for example "DataOutputStream".

 

So far what I've got down is creating the server socket which is just one line of code, creating a boolean and then a do until loop for the main method which keeps the server alive, I then have a hashmap or arraylist which ever works to reference new Player instances, I look for incoming connections and when one is found I store the socket and name in a new object Player then increase the player count. I dont know how to loop for disconnections yet because that requires the player 'pinging' the server every 30 seconds or so. If the server receives it the client is still connected else destroy that player object and decrease player count. 

What I'd like to do next is receive a message from the client, I've created a chatbox on the client and prepared a send message button. My format is msg_type, msg. Msg_type represents an integer from 1-XXX and depending on the message type the server can anticipate a different msg using a switch case statement. This is what I tried..


 

package mypackage;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.io.BufferedReader;
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(5000);//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
            
            run();
        } catch(IOException e){}
    }

    
    
    public void run()
    {
        do
        { //start a do loop while alive is true
            checkForMessages();//check for messages
System.out.println("Run method..");
        }
        while (alive);
    }        
        
    
    private void checkForMessages()
    {
        int received_type;
        String receive_text;
        System.out.println("CheckForMessages method..");
        
        try{
            received_type = input.readInt();
        
        if (received_type != 0)
            {
                System.out.println(received_type);
            }
        
        if (received_type == 1)
                {
            //1 means textmsg
            receive_text = input.readLine();
            System.out.println(receive_text);
                }
        } catch(IOException e){}
        
    }
    
    
}

 

So I'm using data input and dataoutput streams, then remembering the format I'm using msg_type and msg which I call received_type and receive_text, first I check received_type, if it's not == 0 then print the type. If it's equal to 1 then read the next received buffer and print it.

 

My problem is receive_text = input.readLine();

.readline() is deprecated.

It's recommending I use BufferedStream or something like that. 

 

I believe I'm going at reading all wrong here. 

0

Share this post


Link to post
Share on other sites

Programming is pretty hard, especially learning it. I'll have a look at related documentation regarding incoming/outgoing methods first, no need to respond with answers. My main problem right now is with using the right methods from libraries to send and receive data. 

0

Share this post


Link to post
Share on other sites

Naturally I'd print the error message!

I'm not working on the server at the moment, Since I had a problem with BufferedStream I ended up getting some Java books to help me. I see in chapter four it covers BufferedStream how ever I'm only at chapter three now, and it's a huge chapter! I'm fine with that because since I started I've learnt about some fun and interesting concepts.

Eventually the plan is to get to java.io* stuff. So I'll post in this thread once I've gotten back to working on the server. 

0

Share this post


Link to post
Share on other sites

Posted (edited)

Hi again!

 

while (online)
        {
        
            Socket new_Client = server.accept();
            connected_Count += 1;
            if (new_Client != null)
            {
                
                Player p = new Player();
                
                
                new_Client = null;
            }
            
        }
        

So I've got a question regarding this code, This is in my main method, Basically what my idea is to look for a new connecting socket and when one is found or when new_Client has a value then create an object of Player then reset new_Client so that the 'setup code' only happens once per new client.

 

The thing is I also have Socket new_Client at the start, so I'm wondering if Socket new_Client is going to create hundreds of new_Clients instead of use the same one ? because I'm declaring new_Client in the while statement, if so my work around is to declare new_Client before the while statement. 

 

Second thing is I'm getting a message "The value of the local variable connected_Count is not used"

I've declared int connected_Count = 0; at the start of the main method then within the code above you can see I'm incrementing it by one, I also added a println function for connected_Count and still getting that message ? 

Edited by Xer0botXer0
0

Share this post


Link to post
Share on other sites

accept() creates a new socket for every incoming connection it accepts. Obviously once you hit the bottom of the loop that socket goes out of scope, gets destroyed, the connection gets dropped. The same happens if you declare it outside the loop, because if you overwrite that value, the old socket gets destroyed, the connection gets dropped. You'd want to store multiple connections in some sort of data structure. Or maybe store them in the Player, and store the Players in some sort of data structure.

Your message about the value being unused - it's not saying the variable is unused - obviously you increment it - it's saying the value is unused. It's asking "why would a programmer bother incrementing a variable if they never read it or assign it to anything else?" Normally an unused variable means you did something wrong, or forgot to finish something. If you're sure it's not a mistake - because you intend to use it later - ignore it. (Also, don't increment that variable until you know that the socket isn't null.)

0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now