If you need more examples, see
Server | Client |
ServerSocket ss = new ServerSocket(port); Socket s = ss.accept(); DataInputStream in = new DataInputStream(s.getInputStream()); System.out.println("Client connected"); int i = in.readInt(); System.out.println("Got int : " + i); s.close(); System.out.println("Connection closed"); | Socket s = new Socket(addr, port); DataOutputStream out = new DataOutputStream(s.getOutputStream()); System.out.println("Connected to server"); int i = 12345; out.writeInt(i); System.out.println("Sent integer : " + i); s.close(); System.out.println("Closed connection"); |
Client connected Got int : 12345 Connection closed | Connected to server Sent integer : 12345 Closed connection |
Your network implementation will also make use of UDP datagram, allowing racquets, balls etc. to inform other elements of the game of their position, orientation etc. without needing direct connections to each of these other elements. In this section of the application speed is critical. You need to send the critical information in messages that are as small as possible in order to minimise construction and deconstruction time. As such we won't be sending strings over the network. Unfortunately I was not able to find objects similar to DataOutputStream and DataInputStream that allow primitive variables to be converted to byte arrays and then reconstructed from byte arrays. Here are a couple of methods that allow you to convert integers or floats to byte arrays and back again. You should use this lab as an opportunity to test these functions. (btw if anyone does find a way to do this in any of the UDP networking classes I would really like to know.)
/**
Convert an integer to an array of bytes
*/
public byte[] intToBytes(int i)
{
byte b[] = {(byte) (i >> 0), (byte) (i >> 8), (byte) (i >> 16), (byte) (i >> 24)};
return b;
}
/**
Convert an array of bytes to an integer
*/
public int bytesToInt(byte[] b)
{
int i = ((b[0] & 0xff) << 0) + ((b[1] &0xff) << 8) + ((b[2] & 0xff) << 16) + ((b[3] & 0xff) << 24);
return i;
}
/**
Convert a float to an array of bytes
*/
public byte[] floatToBytes(float f)
{
int i = Float.floatToIntBits(f);
return intToBytes(i);
}
/**
Convert an array of bytes to a float
*/
public float bytesToFloat(byte[] b)
{
int i = bytesToInt(b);
float f = Float.intBitsToFloat(i);
return f;
}
By using UDP broadcasting out application will not use up as much network resources as it would if we used TCP peer to peer or TCP client server configurations.
Be carreful to use Multicasting instead of UDP Broadcasting as in this example. See the sun trails for a full example :