• 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.
Sign in to follow this  
Followers 0
Canvas

Java Networking help to understand sockets

15 posts in this topic

Hey there people,

 

I'm trying to create a very basic pong game that can be played over the internet or over a network, now I have the game which can be ran on one computer and two players can play it, so I can split it up into a server and a client, the server will ofcourse hold all of the information, bat position, ball position, score blah blah blah, and the client will just receive the data and use it to display the ball bats and what not.

 

But I have looked around at many tutorials about java networking (most of them are out of date), and I still can't really get my head around it. Many tutorials say to use InputStream and OutputStream, I know an InputStream can read in files and what not, but not sure about OutputStream, now I have seen the socket class in action from tutorials, but I really can't understand that ... well ok so for example

 

 

We have a server like so

 

 

import java.net.*;
import java.io.*;
 
import java.net.*;
import java.io.*;

public class ChatServer
{  private Socket          socket   = null;
   private ServerSocket    server   = null;
   private DataInputStream streamIn =  null;

   public ChatServer(int port)
   {  try
      {  System.out.println("Binding to port " + port + ", please wait  ...");
         server = new ServerSocket(port);  
         System.out.println("Server started: " + server);
         System.out.println("Waiting for a client ..."); 
         socket = server.accept();
         System.out.println("Client accepted: " + socket);
         open();
         boolean done = false;
         while (!done)
         {  try
            {  String line = streamIn.readUTF();
               System.out.println(line);
               done = line.equals(".bye");
            }
            catch(IOException ioe)
            {  done = true;
            }
         }
         close();
      }
      catch(IOException ioe)
      {  System.out.println(ioe); 
      }
   }
   public void open() throws IOException
   {  streamIn = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
   }
   public void close() throws IOException
   {  if (socket != null)    socket.close();
      if (streamIn != null)  streamIn.close();
   }
   public static void main(String args[])
   {  ChatServer server = null;
      if (args.length != 1)
         System.out.println("Usage: java ChatServer port");
      else
         server = new ChatServer(Integer.parseInt(args[0]));
   }
}

And here is the client

import java.net.*;
import java.io.*;

public class ChatClient
{  private Socket socket              = null;
   private DataInputStream  console   = null;
   private DataOutputStream streamOut = null;

   public ChatClient(String serverName, int serverPort)
   {  System.out.println("Establishing connection. Please wait ...");
      try
      {  socket = new Socket(serverName, serverPort);
         System.out.println("Connected: " + socket);
         start();
      }
      catch(UnknownHostException uhe)
      {  System.out.println("Host unknown: " + uhe.getMessage());
      }
      catch(IOException ioe)
      {  System.out.println("Unexpected exception: " + ioe.getMessage());
      }
      String line = "";
      while (!line.equals(".bye"))
      {  try
         {  line = console.readLine();
            streamOut.writeUTF(line);
            streamOut.flush();
         }
         catch(IOException ioe)
         {  System.out.println("Sending error: " + ioe.getMessage());
         }
      }
   }
   public void start() throws IOException
   {  console   = new DataInputStream(System.in);
      streamOut = new DataOutputStream(socket.getOutputStream());
   }
   public void stop()
   {  try
      {  if (console   != null)  console.close();
         if (streamOut != null)  streamOut.close();
         if (socket    != null)  socket.close();
      }
      catch(IOException ioe)
      {  System.out.println("Error closing ...");
      }
   }
   public static void main(String args[])
   {  ChatClient client = null;
      if (args.length != 2)
         System.out.println("Usage: java ChatClient host port");
      else
         client = new ChatClient(args[0], Integer.parseInt(args[1]));
   }
}

 

now when the server is up it waits for a connection, using this line 

socket = server.accept();

first off, is the program stuck in a loop when it does that?

I understand most of this, but not the networking parts, I understand they throw around the OutputStream and InputStream but I'm still not 100% comfortable on my understanding of it :(

 

If anyone could be so kind to explain this to me in basic terms I would be most grateful.

 

Canvas

 

 

 

 

 

0

Share this post


Link to post
Share on other sites

is the program stuck in a loop when it does that?

It's stuck, yes, but not in a loop. It's just blocking in the kernel, waiting for a connection to come in.
0

Share this post


Link to post
Share on other sites

Ok so when the client sends a piece of text, how does the server deal with the information? and as I am converting a pong game, would a String be the best way? 

So looking at this line

console   = new DataInputStream(System.in);

 

when I press enter it sends the message, how?

what is the start method? a thread? it doesn't look like a thread to me.

 

and how does this work?


 try
         {  line = console.readLine();
            streamOut.writeUTF(line);
            streamOut.flush();
         }
0

Share this post


Link to post
Share on other sites
You probably should read through the FAQ for the forum. It answers many of these questions, and has pointers to more other answers.
In general:
Servers and clients generally should use non-blocking I/O of some sort.
Game networking is generally based on binary, efficiently packed packets, not on text formats or object serialization.
0

Share this post


Link to post
Share on other sites

So what would you suggest for me to pass around coordinates to clients? I have been asked to create it using TCP first, then using Multicast, so using an object is good for TCP but I was told sending objects is harder in multicast? Is it bad to use InputStream and OutputStream for networking?

0

Share this post


Link to post
Share on other sites

Is it bad to use InputStream and OutputStream for networking?

For real-time networking, such as games, then it's generally not a great idea. You want full control over the network packets.

Again, the FAQ for this forum will have some suggestions, including how to frame packets over TCP so you know when a full packet has arrived.
0

Share this post


Link to post
Share on other sites

hplus0603 I have looked at the FAQ and alot of the links are dead or link to C++ or another language which is a shame :(, smr I just looked at your link, I have no understanding of that at all so I will look for some tutorials. But also just a quick question, Now hplus you stated that InputStream and OutputStream is not really at all the best way to send data over a game network, could you suggest a method? It would nice :)

 

Canvas

0

Share this post


Link to post
Share on other sites

alot of the links are dead or link to C++ or another language which is a shame

Networking works the same, more or less, no matter what the language. If you're saying that the only language you currently know is Java, then you probably need to learn some C/C++ programming first. Networking, when understood, needs a lot of low-level knowledge, which you'll get by understanding C programming. Then you can learn sockets with C. Then you can apply that to Java.
0

Share this post


Link to post
Share on other sites

Well I understand C++ and Java, but I have not messed around with C at all, I have a month or so to do this :) so Learning C to get all the way to java networking maybe for another time :), But still what way would you go about sending data over a network? and using Multicast? Just so I can research

0

Share this post


Link to post
Share on other sites

ah ok :) maybe why I can't get any information about it, well here is a quick question, Looking at this link here http://docs.oracle.com/javase/tutorial/networking/sockets/clientServer.html it has the code for a server that will commuicate with a user and an upgraded version to handle multiple users, I have ran the code and commented it and at last I'm finaling starting to understand it, but just one little tiny bit I'm still a little confused with, the client and server both have input and output streams of some sort, the server has hold of the clients what? output stream or input stream? and what does the client have a hold of on the server? the servers output stream or input stream? I just can't figure out which stream is used for what :), they seem quite equal.

0

Share this post


Link to post
Share on other sites
My Java is very rusty. I would assume that the client has an output stream that writes to a socket. The server will then have another, connected, socket, which it reads from using an input stream. To return data (over TCP sockets,) the server would then have an output stream connected to the same server-side socket. Finally, data that the server writes ends up received on the client socket, and read from that socket by the client through an InputStream.
0

Share this post


Link to post
Share on other sites

the server has hold of the clients what? output stream or input stream? and what does the client have a hold of on the server? the servers output stream or input stream?

Don't get confused here. The Java Server Socket library is a wrapper for using TCP/IP networking communication. Any socket, whether a client or server socket, has both an input stream and an output stream. It reads data "in" from the input stream and writes data "out" to the output stream. But the server or client doesn't hold a stream from the other code. You can write a client that talks to a Google server and gets the home page. You have no idea what language or operating system Google is using, and that's the point. The TCP/IP protocol handles all that crap for you so you can just write code. And all the (really) low level code is wrapped up in the ServerSocket library.

If you write data to an output stream, then the server would need to read from the output stream if is held a reference to the same stream. But it doesn't work that way, because that would get really difficult. It is client output the input? This stuff's hard enough without something like that to worry about.

Start you server, and accept() a connection, which will block waiting for someone to connect.
Start your client, and try to connect to the server.
The server's accept() will return, and allow the client to connect.
Now the server reads some data. Since there is no data to read (because the client hasn't sent anything) it will block.

Then the client will be connected, and can send data. After sending data, the client will attempt to read() the response, which will block.
The Server will get the request, do something with it, and return a response. The server then tries to read some more data().

The client then reads the response. And so one. I suggest trying to get a simple client that connects to www.google.com and pulls some data before trying to write the server too. Once you know you've got the client working, if it is broke, it's the server.

Have Fun! Edited by Glass_Knife
2

Share this post


Link to post
Share on other sites

Glass_Knife that is awesome mate :), well we have been given a pong game which needs to be converted so, I understand most of it now, but yea, still the inputStream and outputStream is alittle confusing, but I'm going to do some hard debugging and testing using the oracle network tutorial which is a knock knock server :) should help me out

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
Sign in to follow this  
Followers 0