Friday, January 18, 2008

Java Coding Question And Answers

Writing Text to a Socket

try {

BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
wr.write("aString");
wr.flush();
} catch (IOException e) {
}
Sending a Datagram
public static void send(InetAddress dst,int port, byte[] outbuf, int len) {
try {
DatagramPacket request = new DatagramPacket(outbuf, len, dst, port);
DatagramSocket socket = new DatagramSocket();
socket.send(request);
} catch (SocketException e) {
} catch (IOException e) {
}
}

Receiving a Datagram

try {
byte[] inbuf = new byte[256]; // default size
DatagramSocket socket = new DatagramSocket();
// Wait for packet
DatagramPacket packet = new DatagramPacket(inbuf, inbuf.length);
socket.receive(packet);
// Data is now in inbuf
int numBytesReceived = packet.getLength();
} catch (SocketException e) {
} catch (IOException e) { }

Joining a Multicast Group

public void join(String groupName, int port) {
try {
MulticastSocket msocket = new MulticastSocket(port);
group = InetAddress.getByName(groupName);
msocket.joinGroup(group);
} catch (IOException e) { }
}

Receiving from a Multicast Group
public void read(MulticastSocket msocket,byte[] inbuf) {
try {
DatagramPacket packet = new DatagramPacket(inbuf, inbuf.length);
socket.receive(packet); // Wait for packet
// Data is now in inbuf
int numBytesReceived = packet.getLength();
} catch (IOException e) { }
}
Sending to a Multicast Group
byte[] outbuf = new byte[1024];
int port = 1234;
try {
DatagramSocket socket = new DatagramSocket();
InetAddress groupAddr = InetAddress.getByName("228.1.2.3");
DatagramPacket packet = new DatagramPacket(outbuf, outbuf.length, groupAddr, port);
socket.send(packet);
} catch (SocketException e) {
} catch (IOException e) {
}

No comments:

 
Google