Showing posts with label java networking. Show all posts
Showing posts with label java networking. Show all posts

Sunday

DatagramPacket in Java



The DatagramPacket class is a wrapper for an array of bytes from which data will be sent or into which data will be received. It also contains the address and port to which the packet will be sent.
 public DatagramPacket(byte[] data, int length)
 public DatagramPacket(byte[] data, int length, InetAddress host, int port)
You construct a DatagramPacket object by passing an array of bytes and the number of those bytes to send to the DatagramPacket() constructor like this:
 String s = "My first UDP Packet"
  byte[] b = s.getBytes();
  DatagramPacket dp = new DatagramPacket(b, b.length);
Normally you'll also pass in the host and port to which you want to send the packet:
try {
  InetAddress metalab = new InetAddress("netparam.com");
  int chargen = 19;
  String s = "My second UDP Packet"
  byte[] b = s.getBytes();
  DatagramPacket dp = new DatagramPacket(b, b.length, metalab, chargen);
}
catch (UnknownHostException ex) {
  System.err.println(ex);
}
The byte array that's passed to the constructor is stored by reference, not by value. If you cahnge it's contents elsewhere, the contents of the DatagramPacket change as well.
DatagramPackets themselves are not immutable.
You can change the data, the length of the data, the port, or the address at any time with these four methods:
 public void setAddress(InetAddress host)
 public void setPort(int port)
 public void setData(byte buffer[])
 public void setLength(int length)
You can retrieve these items with these four get methods:
 public InetAddress getAddress()
 public int getPort()
 public byte[] getData()
 public int getLength()
These methods are primarily useful when you're receiving datagrams.


Wednesday

URLs to Local Files






The URL class can also be used to access files in the local file system. Thus the URL class can be a handy way to open a file, if you need your code to not know whether the file came from the network or local file system.

Here is an example of how to open a file in the local file system using the URL class: URL url = new URL("file:/c:/data/test.txt");

URLConnection urlConnection = url.openConnection();
InputStream input = urlConnection.getInputStream();

int data = input.read();
while(data != -1){
System.out.print((char) data);
data = input.read();
}
input.close();


Notice how the only difference from accessing a file on a web server via HTTP is the the URL: "file:/c:/data/test.txt".