Java Networking help to understand sockets

Started by
14 comments, last by Canvas 11 years, 2 months ago

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

Advertisement

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.
enum Bool { True, False, FileNotFound };

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();
         }
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.
enum Bool { True, False, FileNotFound };

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?

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.
enum Bool { True, False, FileNotFound };

In Java you'll probably want to use channels for networking.

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

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.
enum Bool { True, False, FileNotFound };

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

This topic is closed to new replies.

Advertisement