Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- import java.net.*;
- import java.util.*;
- public class PeerGNUTELLA
- {
- public static void main(String[] args) throws Exception
- {
- switch(args[0])
- {
- case "client": search(); break;
- case "server": download(); break;
- default: break;
- }
- }
- /* client mode: searches for a file */
- static void search()
- {
- /* connection to peer; the peer ID is saved in "String peerID" */
- Socket clientSocket = new Socket("peerID", 4445);
- /* opening buffers */
- BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
- BufferedReader inputStream = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
- DataOutputStream outputStream = new DataOutputStream(clientSocket.getOutputStream());
- /* search */
- in.readLine(); // the first line is the mode: "client" or "server", and should be skipped
- String searchID = in.readLine();
- byte[] data;
- /* converts user, pwd, and searchID into a packet to be flooded into the network */
- InetAddress networkIP = InetAddress.getByName("hostid");
- /* now that the own IP is known, it is tweaked and .0 is added to the end instead of using the own IP address
- this way, the addressee will be the whole nearby network, including all of the user's nearby peers */
- DatagramSocket searchSocket = new DatagramSocket();
- DatagramPacket packet = new DatagramPacket(data, data.length, networkIP, 4446);
- searchSocket.send(packet);
- /* now the packet is flooded into the network and the nearest neighbour that knows who has the file will respond with the IP address of the file owner */
- /* then, with said IP, another TCP connection (like the one to the first peer) will be established to transfer the file */
- clientSocket.close();
- }
- /* server mode: provides a file to the peer requesting it */
- static void download()
- {
- /* opening connection */
- ServerSocket serverSocket = new ServerSocket(4445);
- while(true)
- {
- Socket clientSocket = serverSocket.accept();
- /* opening buffers */
- BufferedReader inputStream = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
- DataOutputStream outputStream = new DataOutputStream(clientSocket.getOutputStream());
- String clientInput = inputStream.readLine();
- /* processes the request sent by the client and packs the data into a "byte[] data" */
- outputStream.writeBytes(data);
- clientSocket.close();
- }
- serverSocket.close();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement