Quake tools with Java and UDP ... continued
Author: vglass@jfind.com, Van Glass
Now that a socket for sending and receiving data has been established one can create an outgoing DatagramPacket.
The DatagramPacket class is unique in that based on its constructor it can be used to send a UDP packet or receive a UDP packet.
First lets go ahead and create the outgoing DatagramPacket which we will use to issue a "getstatus" request to the Quake server.
String hostname = "10.1.1.1";
int port = 27960;
InetAddress ia = InetAddress.getByName(hostname);
private static byte oob = (byte)0xff;
String command = "xxxxgetstatus";
byte[] buffer = command.getBytes();
* Pad first 4 bytes of buffer to construct
OOB (Out of Band) data packet
*/
for(int i = 0; i < 4; i++)
{
buffer[i] = oob;
}
/* Create outgoing packet */
DatagramPacket outgoing = new DatagramPacket(buffer,buffer.length,ia,port);
Now the DatagramPacket is ready to fire off to the server. The next step is to create a
DatagramPacket which will be used to store the results of the request. Unlike the outgoing packet the incoming
packet only need to be passed any empty buffer and its length in its constructor. The maximum byte size of any UDP packet is 65507 so
an empty byte buffer will be created of this size to store the results.
buffer = new byte[65507];
incoming = new DatagramPacket(buffer,buffer.length);
s
The next step is to go ahead and fire off the outgoing DatagramPacket.
/* Send outgoing packet */
ds.send(outgoing);
Immediately after the send call one should call the receive method on the DatagramSocket
created.
/* Receive results */
ds.receive(incoming);
String message = new String(incoming.getData(),0,0,incoming.getLength());
Again notice how the same instance of a DatagramSocket class is used to process both the
outgoing and incoming data. Once the DatagramSocket receives a response from the server
it places the contents of the response into the empty incoming DatagramPacket.
Next
| Sponsored Links - please visit our sponsors |
| Learn Java Server Faces! | | Use WebGalileo Faces JSF components to quickly create Java based web apps. | | http://www.jscape.com/webgalileofaces/ |
| Java FTP Component | | Easily add FTP to your Java apps. | | http://www.jscape.com/inetfactory/ftp.html |
| SSH Factory | | automate telnet and SSH tasks | | http://www.jscape.com/sshfactory/ |
| FTP Applet | | Add file transfer capabilities to your web pages. | | http://www.jscape.com/ftpapplet/index.html |
Sponsor this site
| |