HackToHell. Powered by Blogger.

Java Program that uses Datagram packet to send a file over LAN

In this program we have a server(noide.java) and a client(noides.java)

This is the server or the broadcaster

import java.nio.*;
import java.nio.channels.*;
import java.io.*;
import java.net.*;
class noide{
public static int serverPort = 998;
public static int clientPort = 999;
public static int buffer_size = 400000;
public static DatagramSocket ds;
public static byte buffer[] = new byte[buffer_size];

public static void main(String args[])throws Exception,IOException{
FileInputStream fln;
FileChannel fchan;
BufferedReader g = new BufferedReader(new InputStreamReader(System.in));
String bh = g.readLine();
long fsize;
ByteBuffer mbuf;
ds = new DatagramSocket(serverPort);

fln = new FileInputStream(bh);
fchan = fln.getChannel();
fsize = fchan.size();
System.out.println( fsize);
mbuf = ByteBuffer.allocate((int) fsize);
fchan.read(mbuf);
int hp;
mbuf.rewind();
for( hp = 0;hp<fsize;hp++)
buffer[hp] = mbuf.get();
ds.send(new DatagramPacket(buffer,hp,InetAddress.getLocalHost(),clientPort));

fchan.close();
fln.close();
}
}

 

As you can see it sends it to the LocalHost(127.0.0.1).It can be changed to work over LAN or over the Internet(port-forwarding required).The client :

import java.nio.*;
import java.nio.channels.*;
import java.io.*;
import java.net.*;
class noides{
public static int serverPort = 998;
public static int clientPort = 999;
public static int buffer_size = 400000;
public static int buffer_siz = 1024;
public static DatagramSocket ds;
public static byte buffer[] = new byte[buffer_size];

public static void main(String args[])throws java.io.IOException{
FileOutputStream fln;
FileChannel fchan;

ByteBuffer mbuf;
ds = new DatagramSocket(clientPort);

fln = new FileOutputStream("tester.txt");

fchan = fln.getChannel();

DatagramPacket  p = new DatagramPacket(buffer,buffer.length);
System.out.println("OK");
        ds.receive(p);
        int hunt = p.getLength();
        mbuf = ByteBuffer.allocate(p.getLength());
        System.out.println(new String(p.getData(),p.getOffset(),p.getLength()));
        mbuf.put(p.getData(),p.getOffset(),p.getLength());

mbuf.rewind();

fchan.write(mbuf);
fchan.close();
fln.close();
}
}

The client must be running before the server is started.

It is saved in tester.txt.

 

Tags:-java program,datagram packet,datagram socket,datagram socket over LAN,server client in Datagram,send a file with Datagram.

Share on Google Plus

About hacktohell

Love technology.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment