Using the Java Networking APIs

java.net

The classes in the package java.net are the original networking APIs for Java. In recent years, alternative APIs have been introduced, but for simple, small-scale networking needs java.net classes can still be the easiest to use and they perform fine. Their biggest limitation is that they require a thread per TCP/IP or UDP socket to read from so they aren’t suitable for applications that listen to a large number of sockets. (Typically, these are server applications expecting numerous users.)

The fundamental class in java.net is the Socket class. Java draws a distinction between TCP/IP sockets that are created to make connections to another computer and TCP/IP sockets that are created to wait for other computers to connect to them. Sockets that initiate connections to other computers are represented by the Socket class. Sockets that accept connections from other computers are represented by the ServerSocket class.

The ServerSocket class is a special sort of factory class. It returns a separate Socket object for every connection that is made to it. Actual communication back and forth is done using these returned Sockets. Thus, a single ServerSocket can set up separate connections for many different communication partners.

There are also classes for UDP sockets (DatagramSocket) and multicast sockets (MulticastSocket.)

In practice, for LAN games it is generally convenient to do all your game communication with Socket and ServerSocket. MulticastSocket is useful for the discovery process, when you find other players to connect to. DatagramSocket can be safely ignored.

To open a TCP/IP connection in Java, all you need to do is create a Socket and tell it to connect. You can then get an input stream from the Socket and read from it as you would any other data source, with one key difference: socket reads are blocking. Therefore, if you try to read data from the Socket and none has arrived yet, the read call will wait for the data. For this reason Sockets are typically given their own thread to run on so that the wait for data doesn’t jam up the whole application.

The SimpleSocketListener sample application does this so waiting for data from one connection doesn’t stop it from processing data coming in from another.

/*****************************************************************************  * Copyright (c) 2003 Sun Microsystems, Inc.  All Rights Reserved.  * Redistribution and use in source and binary forms, with or without  * modification, are permitted provided that the following conditions are met:  *  * - Redistribution of source code must retain the above copyright notice,  *   this list of conditions and the following disclaimer.  *  * - Redistribution in binary form must reproduce the above copyright notice,  *   this list of conditions and the following disclaimer in the documentation *   and/or other materials provided with the distribution.  *  * Neither the name Sun Microsystems, Inc. or the names of the contributors  * may be used to endorse or promote products derived from this software  * without specific prior written permission.  *  * This software is provided "AS IS," without a warranty of any kind.  * ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING  * ANY IMPLIED WARRANT OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR  * NON-INFRINGEMEN, ARE HEREBY EXCLUDED.  SUN MICROSYSTEMS, INC. ("SUN") AND  * ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS  * A RESULT OF USING, MODIFYING OR DESTRIBUTING THIS SOFTWARE OR ITS   * DERIVATIVES.  IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST  * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,  * INCIDENTAL OR PUNITIVE DAMAGES.  HOWEVER CAUSED AND REGARDLESS OF THE THEORY  * OF LIABILITY, ARISING OUT OF THE USE OF OUR INABILITY TO USE THIS SOFTWARE,  * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.  *  * You acknowledge that this software is not designed or intended for us in  * the design, construction, operation or maintenance of any nuclear facility  *  *****************************************************************************/ 

package com.worldwizards.shawnbook; import java.net.ServerSocket; import java.io.*; import java.net.Socket; /** SimpleSocketListener  * This class is a simple application that opens a TCP/IP socket * on port 1138 and prints any data sent there. * * To try it, run the program and then use telnet to connect to port 1138 * on the system on which the app is running.  */ public class SimpleSocketListener {   ServerSocket myServerSocket;   public SimpleSocketListener() {     // Create the Server Socket.  This makes an end-point for     // the telnet sessions to connect to.     try {       myServerSocket = new ServerSocket(1138);     }     catch (IOException ex) {       ex.printStackTrace();     }   }   /**    * listen    */   private void listen() {     while(true) { // loop until program is interrupted       try {         // accept() says "I’m ready to handle a connector"         Socket newConnSocket = myServerSocket.accept();         Thread socketThread = new Thread(         new SocketToStdout(newConnSocket));         socketThread.start();       }       catch (IOException ex) {       }     }   }   static public void main(String[] args) {    new SimpleSocketListener().listen();  } } 

/*****************************************************************************  * Copyright (c) 2003 Sun Microsystems, Inc.  All Rights Reserved.  * Redistribution and use in source and binary forms, with or without  * modification, are permitted provided that the following conditions are met:  *  * - Redistribution of source code must retain the above copyright notice,  *   this list of conditions and the following disclaimer.  *  * - Redistribution in binary form must reproduce the above copyright notice,  *   this list of conditions and the following disclaimer in the documentation  *   and/or other materials provided with the distribution.  *  * Neither the name Sun Microsystems, Inc. or the names of the contributors  * may be used to endorse or promote products derived from this software  * without specific prior written permission.  *  * This software is provided "AS IS," without a warranty of any kind.  * ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING  * ANY IMPLIED WARRANT OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR  * NON-INFRINGEMEN, ARE HEREBY EXCLUDED.  SUN MICROSYSTEMS, INC. ("SUN") AND  * ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS  * A RESULT OF USING, MODIFYING OR DESTRIBUTING THIS SOFTWARE OR ITS   * DERIVATIVES.  IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST  * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES.  HOWEVER CAUSED AND REGARDLESS OF THE THEORY  * OF LIABILITY, ARISING OUT OF THE USE OF OUR INABILITY TO USE THIS SOFTWARE,  * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.  *  * You acknowledge that this software is not designed or intended for us in  * the design, construction, operation or maintenance of any nuclear facility  * *****************************************************************************/ 

package com.worldwizards.shawnbook; import java.net.Socket; import java.io.InputStream; import java.io.*; public class SocketToStdout implements Runnable{   Socket mySocket;   public SocketToStdout(Socket socket) {     mySocket = socket;   }   /**    * run    */   public void run() {     Reader rdr;     try {       InputStream istream = mySocket.getInputStream();       rdr = new InputStreamReader(istream);     }     catch (IOException ex) {       ex.printStackTrace();       return;     }     char[] inchar = new char[1];     while(true){       // blocks til a character is available       try {         rdr.read(inchar);       }       catch (IOException ex1) {         // connection ended.  return         return;       }       System.out.print(inchar[0]);     }   } } 



Practical Java Game Programming
Practical Java Game Programming (Charles River Media Game Development)
ISBN: 1584503262
EAN: 2147483647
Year: 2003
Pages: 171

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net