Java - Bidirectional data transfer using UDP

UDPServer.java


import java.io.*;
import java.net.*;

public class UDPServer implements Runnable {
DatagramSocket socket = null;
DatagramPacket packetOut = null;
DatagramPacket packetIn = null;
BufferedReader readFromKeyBoard = null;
byte[] dataIn;
byte[] dataOut;

public UDPServer() {
try {
readFromKeyBoard = new BufferedReader(
new InputStreamReader(System.in));
dataIn = new byte[1024];
dataOut = new byte[1024];
socket = new DatagramSocket(997);

new Thread(this).start();

InetAddress inetAddress = InetAddress.getLocalHost();
while(true) {
String message = readFromKeyBoard.readLine();
dataIn = message.getBytes();
packetOut = new DatagramPacket(dataIn, message.length(), inetAddress, 999);
socket.send(packetOut);
}
} catch(Exception exp) {
exp.printStackTrace();
}
}

public void run() {
try {
while(true) {
packetIn = new DatagramPacket(dataOut, dataOut.length);
socket.receive(packetIn);
String message = new String(packetIn.getData(), 0, packetIn.getLength());
System.out.println(message);
}
} catch(Exception exp) {
exp.printStackTrace();
}
}

public static void main(String[] args) {
new UDPServer();
}
}



UDPClient.java

import java.io.*;
import java.net.*;

public class UDPClient implements Runnable {
DatagramSocket socket = null;
DatagramPacket packetOut = null;
DatagramPacket packetIn = null;
BufferedReader readFromKeyBoard = null;
byte[] dataIn;
byte[] dataOut;

public UDPClient() {
try {
readFromKeyBoard = new BufferedReader(
new InputStreamReader(System.in));
dataIn = new byte[1024];
dataOut = new byte[1024];
socket = new DatagramSocket(999);

new Thread(this).start();

InetAddress inetAddress = InetAddress.getLocalHost();
while(true) {
String message = readFromKeyBoard.readLine();
dataIn = message.getBytes();
packetOut = new DatagramPacket(dataIn, message.length(), inetAddress, 997);
socket.send(packetOut);
}
} catch(Exception exp) {
exp.printStackTrace();
}
}

public void run() {
try {
while(true) {
packetIn = new DatagramPacket(dataOut, dataOut.length);
socket.receive(packetIn);
String message = new String(packetIn.getData(), 0, packetIn.getLength());
System.out.println(message);
}
} catch(Exception exp) {
exp.printStackTrace();
}
}

public static void main(String[] args) {
new UDPClient();
}
}

Post a Comment

4 Comments

  1. You are a graduate from Barton hills and seems to be a good techie. Why are you working at SBI?? Is it that difficult to get a proper tech job even with credentials like that?

    ReplyDelete
    Replies
    1. True that, I'm working for SBI. However, in its IT Department. There is nothing like proper/improper tech job :)
      Thanks for your concern :)

      Delete
  2. Iam also from Aluva studying Btech at FISAT Angamaly and my school was Cresent public school thottumugham.

    ReplyDelete