(For Six Months Industrial Training

)

By Nitika Sharma

CHAPTER NO.

TITLE

PAGE NO.

TITLE PAGE…………………………………………………………………………………….i ABSTRACT……………………………………………………………………………………..ii ACKNOWLEDGEMENT………………………………………………………………….iii LIST OF TABLES & FIGURES…………………………………………………………iv

1.

INTRODUCTION
1.1 Types of Peer to Peer………………………………………………………………..…...........2 1.1.1 Unstructured P2P…………………………………………………………………………2 1.1.2 Centralized P2P…………………………………………………………………………….3 1.2 Applications………………………………………………………………………..……………….....3 1.3 Advantages…………………..……………………………………………...............................3 1.4 Objective …………………………………………………………………………………………..…....4 1.5 Scope…………………….……………………………………………………………………….………….4

2. FEATURES OF PROJECT…………………………………………………………………………….5 3. HARDWARE & SOFTWARE REQUIREMENTS
3.1 Input Requirements…………………………………….……………………………………..8 3.2 Output Requirements………………………………………………………………………..8
3

3.3 Software Requirements…………………….………………………………………………..8 3.4 Hardware Requirements……………………………………………………………………..8

4. TOOL USED FOR DEVELOPMENT
4.1 NetBeans…………………………………………………………………………….……………….10 4.1.1 Features and Tools…………………..……………………………..………..…….10 4.1.2 Source Code Editor………………………………………………………………….10 4.1.3 GUI Builder………………………………………………………………………………..11

5.

TECHNOLOGY TO BE USED
5.1 Introduction to Java…………………………………………………………..……………..13 5.1.1 Java Virtual Machine……………………………………………….…………..13 5.1.2 Principles………………………………………………………………………………..13 5.1.3 Versions……………………………………….………………………………………...14 5.1.4 Features of Java Language…………………………………………………..14 5.2 Multi Threading………………………………………………………………………….........16 5.2.1 Benefits of using threads……………………………………………………..17 5.2.2 Life Cycle of a Thread……………………………………………………………17 5.2.3 Thread Priority in Java………………………………………………………….18 5.3 Socket Programming in Java……….…………………………………………………..19 5.3.1 Ports and Sockets………………………………………………………………….20 5.4 Networking In Java…………………………………………………………………………….22

6. SOFTWARE DEVELOPMENT LIFE CYCLE
4

6.1 Sotware Development Life Cycle………………………………………………………24 6.2 Different Phases……………………………………………………………………………………..25

7. PROJECT PLANNING
7.1 7.2 7.3 Project Planning & Scheduling ……………………………………………………….26 Sotware Configuration Management…………………………………………….28 Problem Analysis…………………………………………………………………….…………29

8. REQUIREMENT ANALYSIS
8.1 8.2 Requirement Analysis……………………………………………………………………….30 Types of Requirements…………………………………………………………………….32

9. OVERALL NETWORK ARCHITECTURE
9.1 Client/ Server Model…………………………………………...................................33 9.1.1 Client/Server Limitation………………………………………………..………..35 9.2 P2P Architecture………………………………………………………………………..……..36

10. MODULES
10.1 10.2 10.3 10.4 10.5 10.6 Create Main P2P Server …………………………………………………..38 Create Main P2P Client …………… ……………………………………...39 Create Miniserver & Miniclient ………………………………………40 Manage Online or Offline User List………………………………...41 Sharing Files On P2P Network…………………………………………42 Receive Search Request On Server Side ……………………….43
5

10.7 10.8 10.9

Sharing Files On Peers & Sending Results Back …………..44 Downloading File From Other Peer .……………………………..45 Peers Can Chat & Ask Other Peers To Share Files ……..46

11. DESIGN
11.1 Design Phase………………………………………………………………………………..48

12. DATA FLOW DIAGRAMS
12.1 12.2 12.3 12.4 12.5 Introduction……………………………………………………………………………………50 Level - 0 Basic Working ……………………………………………………..………..51 Level – 1 Get List Of Online Clients…………………………………………..52 Sharing Files By Clients………………………………………………………………....52 Downloading Files By Clients From Other Peers………………………53

13. CLASS DIAGRAMS
13.1 Class Diagram Of Main Server………………………………………………………54 13.2 Class Diagram Of Client………………………………………………………………….55

14. GANTT CHART…………………………………………………………………………………………..56 15. SNAPSHOTS & CODING
15.1 Welcome Screen………………………………………………………………………………..58 15.2 P2P Main Server…………………………………………………………………………………59 15.3 Constraints………………………………………………………………………………………….60 15.4 Client GUI…………………………………………………………………………………………….62 15.5 Searching of a file……………………………………………………………………………….64 15.6 Downloading File………………………………………………………………………………..66 15.6.1 To Open Downloading File………………………………………….…………..67
6

15.6.2 Shared Folder……..……………………………………………………………………..68 15.6.3 To Download existing file………………………………………………………..68 15.6.4 To Rename the file…………………………………………………………………...69 Changing the Shared Path……………………………………..………………...71 15.7 15.8 To Test the Speed……………………………………………………………….……..74 15.9 To View Attached Peers………………………………………………….…….....77 15.10 To view Download History……………………………………………….….....79 15.11 To cancel Download…………………………………………………………………80 15.12 Message Sending………………………………………………………………….….83 15.13 Changing Themes……………………………………………………………………86 15.14 Coding of client & inner classes……………………………………….......88

12. FUTURE & FURTHER ENHANCEMENT OF PROJECT…………...........144 13. APPENDIX…………………………………………………………………………………………….…….145 14. BIBLIOGRAPHY………………………………………………………………………………………147

7

LIST OF TABLES & FIGURES
Tables
5.1

Page No.
Thread Priority …………………………………………………………………….............18

Figures
5.1 5.3 Life Cycle Of Thread…………………………………………………………………………..….17 Socket Programming………………………………………………………………………….....19

5.3.1 Connection request from Client………………………………………………..………..20 5.3.2 Connection Build From Server……………………………………………………….......21 5.4 6.1 9.1 Ports help Computer to Identify service………………………………………......22 SDLC Waterfall Model……………………………………………………………………….....24 Client Server Interaction………………………………………………………………………34

9.2.1 P2P Architecture……………………………………………………………………………….....36 11.1 Design Phase………………………………………………………………………………………....48 12.1 Data Flow Diagrams Notations…………………………………………………………….50

8

CHAPTER 1

PEER 2 PEER FILE SHARING SYSTEM WITH CHAT

Page | 1

INTRODUCTION TO THE PROJECT
The project is Java Based Peer to Peer( P2P) File Sharing System with chat.Point-to-Point (P2P) technology enables the sharing of computer resources such as files by a direct exchange between end-users computers. P2P networking means files are not stored on a central server. Instead, client software (such as the popular Kazaa, Limewire) works as a server for shared files on an individual's computer. This allows each computer with the software to act as a mini-server from which other P2P users can download files. P2P's popularity stems from its easy-to-use, convenient setup that has empowered informal networks of file sharers to make files available to each other around the globe.P2P communication has the following characteristics:     Direct connections between network clients Each client (node) is considered as an equal to all others Clients share processing, applications and content There is no central point of control within the network.

Peer-to-peer computing is the sharing of computer resources and services by direct exchange between systems. In a peer-to-peer architecture, computers that have traditionally been used solely as clients communicate directly among themselves and can act as both clients and a server, assuming whatever role is most efficient for the network. Another big attraction of file-sharing is cost : Users can download as many songs as they like from each other, for free. With the price of CDs often well over $20, many music-lovers have engaged in file-sharing despite the legal risks involved. Moreover, many consumers are loath to spend $20 for a compilation of songs when they are really only interested in one of the tracks on the CD. They may turn to file-sharing in order to download the one song that they want, without having to purchase the full CD.

1.1 Types of Peer To Peer Network
1.1.1 Unstructured peer-to-peer network: It do not impose any structure on the
overlay networks. Peers in these networks connect in an ad-hoc fashion. Ideally, unstructured P2P systems would have absolutely no centralized system, but in practice there are several types of unstructured systems with various degrees of centralization.There are two main types of unstructured P2P networks: 

Pure peer-to-peer systems : The entire network consists solely of equipotent
peers. There is only one routing layer, as there are no preferred nodes with any special infrastructure function.
Page | 2

Hybrid peer-to-peer systems: These systems allow such infrastructure nodes to
exist, often called supernodes.A pure P2P network does not have the notion of clients or servers but only equal peer nodes that simultaneously function as both "clients" and "servers" to the other nodes on the network.

1.1.2 Centralized peer-to-peer network: In this, central server is used for indexing
functions and to bootstrap the entire system. Although this has similarities with a structured architecture, the connections between peers are not determined by any algorithm.

1.2 Applications
 Many file sharing networks, such as gnutella, G2 and the eDonkey network popularized peer to peer technologies. From 2004 on, such networks form the largest contributor of network traffic on the Internet.  Peer-to-peer content delivery networks (P2P-CDN). Peer-to-peer content services, e.g. caches for improved performance such as Correli Caches.  Software publication and distribution (Linux, several games) via file sharing networks.

1.3 Advantages
 In P2P networks clients provide resources, which may include bandwidth, storage space and computing power. This property is one of the major advantages of using P2P networks because it makes the setup and running costs very small for the original content distributor. As nodes arrive and demand on the system increases, the total capacity of the system also increases, and the likelihood of failure decreases. If one peer on the network fails to function properly, the whole network is not compromised or damaged. In contrast, in a typical client– server architecture, clients share only their demands with the system, but not their resources. In this case, as more clients join the system, fewer resources are available to serve each client, and if the central server fails, the entire network is taken down.  The decentralized nature of P2P networks increases robustness because it removes the single point of failure that can be inherent in a client-server based system.  Another important property of peer-to-peer systems is the lack of a system administrator. This leads to a network that is easier and faster to setup and keep running because a full staff is not required to ensure efficiency and stability. Decentralized networks introduce new security issues because they are designed so that each user is responsible for controlling their data and resources.A user may encounter harmful data by downloading a file that was originally uploaded as a virus disguised in an .exe, .mp3, .avi, or any other filetype.
Page | 3

1.4 Objective
The objective of the Project is to allow users to download media files such as music, movies, and games using a P2P software client that searches for other connected computers. The "peers" are computer systems connected to each other through the Internet. Thus, the only requirements for a computer to join peer-to-peer networks are an Internet connection and P2P software. The first generation of P2P software is Napster, a central server-based model that was eventually shut down. The second generation of P2P software is Gnutella and Kazaa ,which are user-based models. BitTorrent became the third generation of P2P networks. File transfers involve two computers, often designated as a client and a server and most operations are for the copying files from one machine to another.Most WEB and FTP servers are punished for being popular. Since all uploading is done from one central place, a popular site needs more resources (CPU and bandwidth) to be able to cope. With the use of P2P, the clients automatically mirror the files they download, easing the publisher's burden. Peer to Peer File Sharing System allows peers to search , download and upload files to other peers by just having the list of online clients from server. Peers manage on their own for downloading files.A chat feature is also added so that they can chat with their friends.

1.5 Scope
You can configure computers in peer to peer workgroups to allow sharing of files, printers and other resources across all of the devices. Peer networks allow data to be shared easily in both directions, whether for downloads to your computer or uploads from your computer. On the Internet, peer to peer networks handle a very high volume of file sharing traffic by distributing the load across many computers. Because they do not rely exclusively on central servers, P2P networks both scale better and are more resilient than client-server networks in case of failures or traffic bottlenecks. Peer to peer networking is common on small local area networks (LANs), particularly home networks. Both wired and wireless home networks can be configured as peer to peer environments. Computers in a peer to peer network run the same networking protocols and software. Peer networks are also often situated physically near to each other, typically in homes, small businesses or schools. Some peer networks, however, utilize the Internet and are geographically dispersed worldwide.

Page | 4

CHAPTER 2

FEATURES OF PROJECT

Page | 5

FEATURES OF PROJECT

There are several features of P2P file sharing system: 1. Creating Main P2P Server. 2. Creating Main P2P Client. 3. Creating Miniserver on P2P Client. 4. Creating Miniclient on P2P Client. 5. Manage online or offline user Lists in real time. 6. Sharing files on P2P Network. 7. Receive search request. 8. Search file on peers and sending results to other peer, who made search request. 9. Downloading File from other peer. 10. Uploading file to other. 11.Peers can change their Shared Path 12. Peers can chat and ask other peer to share files. 13. View Attached Peers. 14. To View the download history. 15. To check the link speed of uploading clients. 16.Peer can cancel downloading of the file. Last but not the least feature is : Peers can change the themes of client GUI according to their choice.

Page | 6

CHAPTER 3

HARDWARE & SOFTWARE REQUIREMENTS

Page | 7

3.1 INPUT REQUIREMENTS
The Point-to-Point sharing System will have a minimum set of following requirements:  Login: Whenever user tries to connect to the server it must provide a valid I.P address to access the server. On the basis of server address either the user i.e. client system is connected to the server or denied the access.  Online-clients: Once the client and server gets successfully connected the next thing that is mandatory for the system is that server must show the list of the clients that are active that time. It is important because some of the clients may be down so the user must not keep accessing the offline clients.  Search: Once the online clients are displayed the interface must provide the facility to search the file. Search file should have the functionality that it must indicate the paths of all the system that have that file as specified by the user.  Selection: After listing the user should select one client that he/she finds the best and enables downloading.  Downloading: While the downloading starts, progress bar keeps on indicating that the file has been downloaded successfully or not.

3.2 OUTPUT REQUIREMENTS
The Point-to-Point sharing System has a minimum set of following output requirements:  Space: Downloading client must have surplus space at his\her HDD(C:\shared folder)  Message: Successful downloading of a particular file is indicated by a message at the monitor screen of the downloading client.

3.3 SOFTWARE REQUIREMENTS
 Windows , LINUX , Macintosh  Java Virtual Machine

3.4 HARDWARE REQUIRMENTS
 Pentium 4 Computer  256 MB RAM  High Speed Internet Connection(DSL/Cable)
Page | 8

CHAPTER 4

TOOL USED FOR DEVELOPMENT

Page | 9

4.1 NETBEANS
NetBeans is an IDE (Interactive Development Environment) Software which has been used in this project to make the software. The NetBeans IDE is an open-source integrated development environment written entirely in Java using the NetBeans Platform. NetBeans IDE supports development of all Java application types out of the box. NetBeans is a user-friendly interactive software for Java based applications. This can be downloaded from the company’s website for free. The advantage of using NetBeans is that we can build and run the project in same interface window. The NetBeans Platform allows applications to be developed from a set of modular software components called modules. A module is a Java archive file that contains Java classes written to interact with the NetBeans Open APIs and a manifest file that identifies it as a module. Applications built on modules can be extended by adding new modules. Since modules can be developed independently, applications based on the NetBeans platform can be extended by third party developers.. Using an Integrated Development Environment (IDE) for developing applications saves you time by managing windows, settings, and data. In addition, an IDE can store repetitive tasks through macros and abbreviations. Drag-and-drop features make creating graphical user interface (GUI) components or accessing databases easy, and highlighted code and debugging features alert you to errors in code. NetBeans provides the services common to creating desktop applications -- such as window and menu management, settings storage -- and is also the first IDE to fully support JDK 6.0 features. The NetBeans platform and IDE are free for commercial and noncommercial use, and they are supported by Sun Microsystems.

4.1.1 Features and Tools
The NetBeans IDE has many features and tools for each of the Java platforms. Those in the following list are not limited to the Java SE platform but are useful for building, debugging, and deploying applications and applets :

4.1.2 Source Code Editor
     Syntax highlighting for Java, JavaScript, XML, HTML, CSS, JSP, IDL Customizable fonts, colors, and keyboard shortcuts Live parsing and error marking Pop-up Javadoc for quick access to documentation Advanced code completion
Page | 10

      

Automatic indentation, which is customizable Word matching with the same initial prefixes Navigation of current class and commonly used features Macros and abbreviations Goto declaration and Goto class Matching brace highlighting JumpList allows you to return the cursor to previous modification

4.1.3 GUI Builder
             Fully WYSIWYG designer with Test Form feature Support for visual and nonvisual forms Extensible Component Palette with preinstalled Swing and AWT components Component Inspector showing a component's tree and properties Automatic one-way code generation, fully customizable Support for AWT/Swing layout managers, drag-and-drop layout customization Powerful visual editor Support for null layout In-place editing of text labels of components, such as labels, buttons, and text fields JavaBeans support, including installing, using, and customizing properties, events, and customizers Visual JavaBean customization -- ability to create forms from any JavaBean classes Connecting beans using Connection wizard Zoom view ability

Page | 11

CHAPTER 5

TECHNOLOGY TO BE USED

Page | 12

5.1 INTRODUCTION TO JAVA
Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities. Java applications are typically compiled to byte code (class file) that can run on any Java Virtual Machine (JVM) regardless of computer architecture. Java is a general-purpose, concurrent, class-based, object-oriented language that is specifically designed to have as few implementation dependencies as possible. It is intended to let application developers "write once, run anywhere" (WORA), meaning that code that runs on one platform does not need to be recompiled to run on another. Java is currently one of the most popular programming languages in use, particularly for client-server web applications, with a reported 10 million users.The original and reference implementation Java compilers, virtual machines, and class libraries were developed by Sun from 1995. Main advantage of java programming language is platform independence, which means any application written in java can be operated on any of the platform, instead of having to produce separate versions of the application for each computer and operating system.

5.1.1 Java virtual machine
A Java virtual machine (JVM) is a virtual machine capable of executing Java bytecode.A Java virtual machine is software that is implemented on virtual and non-virtual hardware and on standard operating systems. A JVM provides an environment in which Java bytecode can be executed, enabling such features as automated exception handling, which provides "root-cause" debugging information for every software error (exception), independent of the source code. A JVM is distributed along with a set of standard class libraries that implement the Java application programming interface (API). Appropriate APIs bundled together with JVM form the Java Runtime Environment (JRE).The use of the same bytecode for all JVMs on all platforms allows Java to be described as a "write once, run anywhere" programming language, as opposed to "write once, compile anywhere", which describes cross-platform compiled languages. Thus, the JVM is a crucial component of the Java platform.

5.1.2 Principles
There were five primary goals in the creation of the Java language :  It should be "simple, object-oriented and familiar"  It should be "robust and secure"  It should be "architecture-neutral and portable"  It should execute with "high performance"  It should be "interpreted, threaded, and dynamic"
Page | 13

5.1.3 Versions
Major release versions of Java, along with their release dates :  JDK 1.0 (January 23, 1996)  JDK 1.1 (February 19, 1997)  J2SE 1.2 (December 8, 1998)  J2SE 1.3 (May 8, 2000)  J2SE 1.4 (February 6, 2002)  J2SE 5.0 (September 30, 2004)  Java SE 6 (December 11, 2006)  Java SE 7 (July 28, 2011)

5.1.4 Features of Java Language
The basic features that make Java a powerful and popular programming language:  Platform Independence: The Write-Once-Run-Anywhere ideal has not been achieved, but closer than with other languages.  Object Oriented: Object oriented throughout - no coding outside of class definitions, including main(). An extensive class library available in the core language packages.  Compiler/Interpreter Combo: Code is compiled to bytecodes that are interpreted by a Java virtual machines (JVM) .This provides portability to any machine for which a virtual machine has been written.The two steps of compilation and interpretation allow for extensive code checking and improved security.  Automatic Memory Management : Automatic garbage collection - memory management handled by JVM.  Security  No memory pointers  Programs run inside the virtual machine sandbox.  Dynamic Binding : The linking of data and methods to where they are located, is done at run-time.New classes can be loaded while a program is running. Linking is done on the fly.
Page | 14

 Good Performance : Interpretation of byte codes slowed performance in early versions, but advanced virtual machines with adaptive and just-in-time compilation and other techniques now typically provide performance up to 50% to 100% the speed of C++ programs.  Threading : Lightweight processes, called threads, can easily be spun off to perform multiprocessing.Can take advantage of multiprocessors where available.Great for multimedia displays.  Built-in Networking : Java was designed with networking in mind and comes with many classes to develop sophisticated Internet communications.  Several features of C & C++ eliminated:  No memory pointers  No preprocessor  Array index limit checking Features such as eliminating memory pointers and by checking array limits greatly help to remove program bugs. The garbage collector relieves programmers of the big job of memory management. These and the other features can lead to a big speedup in program development compared to C/C++ programming.  Java I/O Routines : Java provides several tools for the input and output of data, ranging from the Abstract Window Toolkit (AWT) or the Swing Components to the core System functions of Java classes. The AWT is exactly what it says it is: a set of components for designing windows and graphical user interfaces that uses the peer components of the underlying operating system for their implementation.  Streams : Java provides several different kinds of streams, each designed to handle a different kind of data. The standard input and output streams form the basis for all the others.InputStream and OutputStream are both available for you to use as is, or you can derive more complicated stream schemes from them. In order to create the other kinds of Java streams, first you must create and define the basic streams. Perhaps the most-used stream formats are the DataInputStream and the DataOutputStream. Both of these streams enable you to read or write primitive data types, giving you the flexibility within your application to control the results of your application's execution. Without this kind of functionality, you would have to write specific bytes rather than reading specific data.  Input and Output Using System Class: One of the classes Java includes in every applet or application, whether you specify that it do so or not, is the System class. The System class
Page | 15

provides support for input/output (I/O) using the Java console; you are to provide the ability to write to the console, read from the console, and write errors to the user. The Java console is provided in two ways, one for browsers and one for applications. In the browser environment the console is a separate browser window that has controls for scrolling and clearing. For applications run from the operating system (OS) command line, the console is the text interface you see and suffers the same problems as the text base OS environment (lack of scrolling backwards Input Using the System Class Input in the System class is actually handled by the InputStream class contained in the Java I/O routines. System.in is an object of type InputStream that is created, maintained, and initialized by the System class. In other words, it's yours for the taking; you don't have to do a thing to use it. Output Using the System Class As with input, output is handled through streams. How can output be a stream if a stream is a sequence of characters from a source? Well, the source is your application, and the stream is routed to a device known as the standard output. The standard output is usually your monitor, but it could be other things as well. Most notably, the standard output is set to be the Java console when an applet runs within Netscape Navigator.

5.2 Multi-threading in Java
Nearly every operating system supports the concept of processes -- independently running programs that are isolated from each other to some degree. Threading is a facility to allow multiple activities to coexist within a single process. Most modern operating systems support threads, and the concept of threads has been around in various forms for many years. Java is the first mainstream programming language to explicitly include threading within the language itself, rather than treating threading as a facility of the underlying operating system. Threads are sometimes referred to as lightweight processes. Like processes, threads are independent, concurrent paths of execution through a program, and each thread has its own stack, its own program counter, and its own local variables. However, threads within a process are less insulated from each other than separate processes are. They share memory, file handles, and other per-process state.A process can support multiple threads, which appear to execute simultaneously and asynchronously to each other. Multiple threads within a process share the same memory address space, which means they have access to the same variables and objects, and they allocate objects from the same heap. The Java thread facility and API is deceptively simple. However, writing complex programs that use threading effectively is not quite as simple. Because multiple threads coexist in the same memory space and share the same variables, you must take care to ensure that your threads don't interfere with each other.Multithreading enables
Page | 16

you to write very efficient programs that make maximum use of the CPU, because idle time can be kept to a minimum.

5.2.1 Benefits of using threads: The Java language includes a powerful threading facility
built into the language. The threading facility can be used to:  Increase the responsiveness of GUI applications  Take advantage of multiprocessor systems  Simplify program logic when there are multiple independent entities  Perform blocking I/O without blocking the entire program When multiple threads execute byte-code instruction sequences in the same program, that action is known as multithreading.

5.2.2 Life Cycle of a Thread : A thread goes through various stages in its life cycle. For
example, a thread is born, started, runs, and then dies. Following diagram shows complete life cycle of a thread.

Figure 5.1: Life Cycle of Thread
Page | 17

5.2.3 Thread Priority In Java
In Java, thread scheduler can use the thread priorities in the form of integer value to each of its thread to determine the execution schedule of threads . Thread gets the ready-to-run state according to their priorities. The thread scheduler provides the CPU time to thread of highest priority during ready-to-run state. Priorities are integer values from 1 (lowest priority given by the constant Thread.MIN_PRIORITY) to 10 (highest priority given by the constant Thread.MAX_PRIORITY). The default priority is 5 (Thread.NORM_PRIORITY).

Table 5.1 : Thread Priority
METHODS setPriority( ) getPriority( ) DESCRIPTION This is method is used to set the priority of thread. This is method is used to get the priority of thread.

Multithreading benefits a program in various ways:
 Multithreaded GUI (graphical user interface)-based programs remain responsive to users while performing other tasks, such as repaginating or printing a document.  Threaded programs typically finish faster than their non-threaded counterparts. This is especially true of threads running on a multiprocessor machine, where each thread has its own processor.Java accomplishes multithreading through its java.lang.Threadclass. Each Thread object describes a single thread of execution. That execution occurs in Thread's run() method. Because the default run() method does nothing, you must subclass Thread and override run() to accomplish useful work.

Multithreading has several advantages over Multiprocessing such as:
 Threads are lightweight compared to processes  Threads share the same address space and therefore can share both data and code  Context switching between threads is usually less expensive than between processes  Cost of thread intercommunication intercommunication is relatively low that that of process

 Threads allow different tasks to be performed concurrently.
Page | 18

5.3 Socket Programming
URLs and URLConnections provide a relatively high-level mechanism for accessing resources on the Internet. Sometimes your programs require lower-level network communication, for example, when you want to write a client-server application.In client-server applications, the server provides some service, such as processing database queries or sending out current stock prices. The client uses the service provided by the server, either displaying database query results to the user or making stock purchase recommendations to an investor. The communication that occurs between the client and the server must be reliable. That is, no data can be dropped and it must arrive on the client side in the same order in which the server sent it. TCP provides a reliable, point-to-point communication channel those client-server applications on the Internet use to communicate with each other. To communicate over TCP, a client program and a server program establish a connection to one another. Each program binds a socket to its end of the connection. To communicate, the client and the server each reads from and writes to the socket bound to the connection.

Figure 5.3 : Socket Programming
Syntax
// for tcp client side Socket s= new Socket (InetAddress adr, int port); //for server side ServerSocket ss= new ServerSocket (InetAddress adr, int port);
Page | 19

5.3.1 Ports and Sockets
These entities lie at the heart of network communications. For anybody not already familiar with the use of these terms in a network programming context, the two words very probably conjure up images of hardware components. Port: A port is a logical connection to a computer (as opposed to a physical connection) and is identified by a number in the range 1-65535. This number has no correspondence with the number of physical connections to the computer, of which there may be only one (even though the number of ports used on that machine may be much greater than this). Ports are implemented upon all computers attached to a network. Each port may be dedicated to a particular server/service (though the number of available ports will normally greatly exceed the number that is actually used). Port numbers in the range 1-1023 are normally set aside for the use of specified standard services. For example, port 80 is normally used by Web servers for HTTP. In most applications, of course, there are likely to be multiple clients wanting the same service at the same time. A common example of this requirement is that of multiple browsers (quite possibly thousands of them) wanting Web pages from the same server. The server, of course, needs some way of distinguishing between clients and keeping their dialogues separate from each other. This is achieved via the use of sockets. Socket: Normally, a server runs on a specific computer and has a socket that is bound to a specific port number. The server just waits, listening to the socket for a client to make a connection request. A socket is one end-point of a two-way communication link between two programs running on the network. Socket classes are used to represent the connection between a client program and a server program. The java.net package provides two classes--Socket and ServerSocket--that implement the client side of the connection and the server side of the connection, respectively. On the client-side: The client knows the hostname of the machine on which the server is running and the port number on which the server is listening. To make a connection request, the client tries to rendezvous with the server on the server's machine and port. The client also needs to identify itself to the server so it binds to a local port number that it will use during this connection. This is usually assigned by the system.

Figure 5.3.1 : Client side
Page | 20

If everything goes well, the server accepts the connection. Upon acceptance, the server gets a new socket bound to the same local port and also has its remote endpoint set to the address and port of the client. It needs a new socket so that it can continue to listen to the original socket for connection requests while tending to the needs of the connected client.

Figure 5.3.1 : Server side
On the client side, if the connection is accepted, a socket is successfully created and the client can use the socket to communicate with the server. The client and server can now communicate by writing to or reading from their sockets. The following steps occur when establishing a TCP connection between two computers using sockets:  The server instantiates a ServerSocket object, denoting which port number communication is to occur on.  The server invokes the accept() method of the ServerSocket class. This method waits until a client connects to the server on the given port.  After the server is waiting, a client instantiates a Socket object, specifying the server name and port number to connect to.  The constructor of the Socket class attempts to connect the client to the specified server and port number. If communication is established, the client now has a Socket object capable of communicating with the server.  On the server side, the accept() method returns a reference to a new socket on the server that is connected to the client's socket.

Page | 21

5.4 NETWORKING IN JAVA
The Internet is composed of millions of computers, located all across the globe; each of these computers will have a unique IP address.IP addresses are 32-bit numbers, containing four octets (8 bit numbers) separated by a full stop. Each computer with a direct internet connection will have a unique IP address, (e.g. 207.68.156.61). Some computers have temporary addresses, such as when you connect to your ISP through a modem. Others have permanent addresses, and some even have their own unique domain names (e.g. www.microsoft.com).For example, most web servers use port 80. Of course, you can use any port you like – there’s no rule that says you must use 80.

Figure 5.4: Ports help computers to identify which service data is for Advantages of Networking
Networking has a lot of advantages over traditional advertising and marketing. These are the most important advantages:  More business : As you develop networking skills and contacts, you’ll find that the amount of work you get from referrals accounts for the largest part of your new business. And the most profitable.  Better business : The business you get from referrals will usually be from happy customers. This will mean that your best customers, those who pay on time and without headaches, will be the ones who send you the additional business.  Cost savings : As you get more business through referrals, you’ll find less and less need to advertise and market your business. This means less of the associated costs. And since you’ll be getting better quality business, it means less bad debts.

Page | 22

CHAPTER 6

SOFTWARE DEVELOPMENT LIFE CYCLE

Page | 23

6.1 Software Development Life Cycle (SDLC)
The Systems Development Life Cycle (SDLC) is a conceptual model used in project management that describes the stages involved in an information system development project from an initial feasibility study through maintenance of the completed application. Some methods work better for specific types of projects, but in the final analysis, the most important factor for the success of a project may be how closely particular plan was followed. The image below is the classic Waterfall model methodology, which is the first SDLC method and it describes the various phases involved in development.

Figure 6.1 : The SDLC Waterfall Model

The relationship of each stage to the others can be roughly described as a waterfall, where the outputs from a specific stage serve as the initial inputs for the following stage. During each stage, additional information is gathered or developed, combined with the inputs, and used to produce the stage deliverables.

Page | 24

6.2 Different Phases
System planning
The system planning is used to determine if the project should get the go-ahead. If the project is to proceed, the system plan will produce a project plan and budget estimates for the future stages of development.

Requirement Analysis and Design
Analysis gathers the requirements for the system. Design focuses on high level design like, what programs are needed and how are they going to interact. During these phases, the software's overall structure is defined. Analysis and Design are very crucial in the whole development cycle. The logical system of the product is developed in this phase.

Development and Coding
In this phase the designs are translated into code. Computer programs are written using a conventional programming language. Various Programming tools are used to generate the code. Different high level programming languages like PHP, Java are used for coding.

Integration and Testing
In this phase the system is tested. Normally programs are written as a series of individual modules, this subject to separate and detailed test. The system is then tested as a whole. The separate modules are brought together and tested as a complete system. The system is tested to ensure that interfaces between modules work together.

Maintenance
Inevitably the system will need maintenance. Software will definitely undergo change once it is delivered to the customer. Change could happen because of some unexpected input values into the system. In addition, the changes in the system could directly affect the software operations. The software should be developed to accommodate changes that could happen during the post implementation period.

Page | 25

CHAPTER 7

PROJECT PLANNING & PROBLEM ANALYSIS

Page | 26

7.1 PROJECT PLANNING & SCHEDULING
The planning stage establishes a bird’s eye view of the intended software product, and uses this to establish the basic project structure, evaluate feasibility and risks associated with the project, and describe appropriate management and technical approaches” Project planning is part of Project Management. It is a well-established approach to managing and controlling the introduction of new initiatives or organizational changes. Projects are finite in length, usually one-time pieces of work involving a number of activities that must be completed within a given time frame, and often on a fixed budget. While the very simplest projects can be managed easily by applying common sense and just getting on with things, projects that are more complex need a great deal of planning, and benefit from a formal, disciplined management approach. From making sure that activities will actually meet the specified need, to devising a workable schedule, developing systems for reporting progress, and managing requests for changes – all of these issues require thoughtful consideration. Managing projects well requires a great deal of time, skill, and finesse. There are many sides to project management and this is what makes it so interesting and demanding

Project Planning includes:
 Dividing the project into plannable stages  When to build the project plan  Who constructs the project plan  Step by step guide to constructing a project plan  Making the project plan visible, getting the project plan used  Independent project plan reviews  Getting resource commitments  Time recording  Tracking progress against the project plan  Revising the project plan during the project

Page | 27

7.2 SOFTWARE CONFIGURATION MANAGEMENT
Software Configuration Management (SCM) is the task of tracking and controlling changes in the software. Configuration management practices include revision control and the establishment of baselines.Software Configuration Management Software (SCM) is a set of activities that are designed to control change by identifying the work products that are likely to change, establishing relationships among them, defining mechanisms for managing different versions of work products, controlling changes that are imposed, and auditing and reporting on the changes that are made”. SCM is a best tool to manage change to our software systems. However, even with the best of intentions, software projects continue to fail because of problems that could have been avoided through the use of an SCM tool and appropriate processes. These failures are reflected in poor quality, late delivery, cost overruns, and the incapability to meet customer demands. All these flaws are removed by Software Configuration Management (SCM). This Software was developed by four developers (Gagandeep, Navdeep, Nitika).We make this project together by putting our full efforts and hard work. We completed this project in six months. We have worked for at least 5 hours in a day. We also have Java classes daily. While making project we follow the stages like Project Planning, Design and Coding, Integration and Testing.

Goals
The goals of SCM are generally: Configuration identification – Identifying configurations, configuration items and baselines. Configuration control – Implementing a controlled change process. This is usually achieved by setting up a change control board whose primary function is to approve or reject all change requests that are sent against any baseline. Configuration status accounting – Recording and reporting all the necessary information on the status of the development process. Process management – Ensuring adherence to the organization’s development process.
Page | 28

7.3 PROBLEM ANALYSIS
To understand the nature of the system to be built, the system engineer or “Analyst” must understand the information domain for the software, as well as required function, behavior, performance and interfacing. The essential purpose of this phase is to find the need and to define the problem that needs to be solved. In requirement analysis following questions are answered1. What the problem is? The problem is to develop a Peer to Peer Network which enables the sharing of computer resources and services by direct exchange of information. Accessing these decentralized resources means operating in an environment of unstable and unpredictable IP addresses P2P nodes must operate outside the DNS system and have significant, or total autonomy from central servers.

2. Why we need Peer to Peer Network?
It is a model of communication where every node in the network acts alike.As opposed to the client –Server Model where one provide services and other use the services. A distributed network architecture may be called a P2P network if the participants share a part of their own resources. These shared resources are necessary to provide the service offered by the network. The participants of such a network are both resource providers and resource consumers.

3. Whether the problem is worth solving or not?
i. ii. iii. iv. All nodes are both clients and server that provide and consume data. Any peer can initiate a connection. No centralized data source The ultimate form of democracy on the Internet

Page | 29

CHAPTER 8

REQUIREMENT ANALYSIS

Page | 30

8.1 REQUIREMENT ANALYSIS
Requirement Analysis in systems engineering and software engineering, encompasses those tasks that go into determining the needs or conditions to meet for a new or altered product, taking account of the possibly conflicting requirements of the various stakeholders, such as beneficiaries or users. Requirement analysis is critical to the success of a development project. Requirements must be documented, actionable, measurable, testable, related to identified business needs or opportunities, and defined to a level of detail sufficient for system design. Requirements can be functional and non-functional. Any coherent and reasonable system must have requirements that define what the system is ultimately supposed to do. A requirement is an objective that must be met. Planners cast most requirements in functional terms, leaving design and implementation details to the developers. In this Peer to Peer Network, we implemented this phase of requirements gathering by collecting information from various sources like existing systems and network managers who manage their networks.  Evaluation of the existing system and procedures We studied the features of various existing Peer to Peer network such as Napster,Gneutlla which helped us in identifying its capabilities, Architecture of p2p, its graphical user interface design, how data is shared and used by the peers. We tried to answer following questions in requirement gathering phase Who all can use this software?  How will they use the software?  In which networks is this software successful?  How to connect clients through sockets ?  How the data will be share by peers?  How data packets travel along the network? These and many more such questions were there while starting the project and all such questions got answered during the requirements’ gathering phase. This produced a nice big list of functionality that the system should provide, which described functions the system will perform. Conceptually, requirements analysis includes three types of activity:
Page | 31

Eliciting requirements: the task of communicating with customers and users to determine what their requirements are. This is sometimes also called requirements gathering. Analyzing requirements: determining whether the stated requirements are unclear, incomplete, ambiguous, or contradictory, and then resolving these issues. Recording requirements: Requirements might be documented in various forms, such as natural-language documents, use cases, user stories, or process specifications

 

8.2 Types of Requirements
 Customer Requirements
Statements of fact and assumptions that define the expectations of the system in terms of mission objectives, environment, constraints, and measures of effectiveness and suitability (MOE/MOS). The customers are those that perform the eight primary functions of systems engineering, with special emphasis on the operator as the key customer.

 Architectural Requirements
Architectural requirements explain what has to be done by identifying the necessary system architecture of a system.

 Structural Requirements
Structural requirements explain what has to be done by identifying the necessary structure of a system.

 Behavioral Requirements
Behavioral requirements explain what has to be done by identifying the necessary behavior of a system.

 Functional Requirements
Functional requirements explain what has to be done by identifying the necessary task, action or activity that must be accomplished. Functional requirements analysis will be used as the toplevel functions for functional analysis.

 Non-functional Requirements
Non-functional requirements are requirements that specify criteria that can be used to judge the operation of a system, rather than specific behaviors.
Page | 32

CHAPTER 9

OVERALL NETWORK ARCHITECTURE

Page | 33

OVERALL NETWORK ARCHITECTURE

9.1 Client-Server Model
The client/server model is a computing model that acts as distributed application which partitions tasks or workloads between the providers of a resource or service, called servers, and service requesters, called clients.[1] Often clients and servers communicate over a computer network on separate hardware, but both client and server may reside in the same system. A server machine is a host that is running one or more server programs which share their resources with clients. A client does not share any of its resources, but requests a server's content or service function. Clients therefore initiate communication sessions with servers which await incoming requests.

Figure 9.1 : Schematic clients-server interaction
The interaction between client and server is often described using sequence diagrams. The Unified Modeling Language has support for sequence diagrams. Specific types of clients include web browsers, email clients The client/server characteristic describes the relationship of cooperating programs in an application. The server component provides a function or service to one or many clients, which initiate requests for such services. Functions such as email exchange, web access and database access, are built on the client/server model. Users accessing banking services from their computer use a web browser client to send a request to a web server at a bank. That program may in turn forward the request to its own database client program that sends a request to a database server at another bank computer to retrieve the account information. The balance is returned to the bank database client, which in turn serves it back to the web browser client displaying the results to the user. The client–server model has become one of the central ideas of network computing. Many business applications being written today use the client–server model. So do the Internet's main application protocols, such as HTTP, SMTP, Telnet, and DNS and online chat clients. Specific types of servers include
Page | 34

web servers, ftp servers, application servers, database servers, name servers, mail servers, file servers, print servers, and terminal servers. Most web services are also types of servers. In a traditional client/server setup, your home PC acts as a client and sends requests to machines- servers-- somewhere inside the cloud of the Internet to get things done: browsing the web or getting email. In a P2P paradigm, on the other hand, your home PC (for example) may connect, through the Internet, directly to tens or hundreds of other home PCs (or other machines at the 'edge') in order to share information and data. Some of the issues that need to be handled in such a situation include:  Connectivity: how to find and connect other P2P nodes that are running in the network (unlike traditional servers, they don't have a fixed, known IP address)  Instability: nodes may always be joining and leaving the network (unlike servers-- web, email, etc., which we usually depend on to "be there")  Message routing: how messages should be routed to get from one node to another (where the two nodes may not directly know about each other)  Searching (somewhat related to routing): how to find desired information from the nodes connected to the network

9.1.1 Client / Server Limitations
 Scalability is hard to achieve  Presents a single point of failure  Requires administration  Unused resources at the network edge  P2P systems try to address these limitations

Page | 35

9.2 P2P ARCHITECTURE

Figure 9.2.1 P2P Architecture Features
 All nodes are both clients and servers  Provide and consume data  Any node can initiate a connection  No centralized data source  “The ultimate form of democracy on the Internet

P2P Network Characteristics
 Clients are also servers and routers  Nodes contribute content, storage, memory, CPU  Nodes are autonomous (no administrative authority)  Network is dynamic: nodes enter and leave the network “frequently”  Nodes collaborate directly with each other (not through well-known servers)  Nodes have widely varying capabilities
Page | 36

CHAPTER 10

MODULES

Page | 37

MODULES

.1

Create Main Peer to Peer server

CLIENT 1

CLIENT 2

P2P SERVER WILL CONTAIN ALL THE INFORMATION ABOUT THE PEER

CLIENT 4

CLIENT 3

In this module, numbers of clients are connected to the main peer to peer server. In this, P2P server will contain all the information about the connected peer. In this module we have created a one main class P2PServerGUI in which we have two inner classes : p2pserver & client handler.

Page | 38

.2

Create Main Peer 2 Peer Client

Main Client

Main Client

192.168.137.21 192.168.137.78 192.168.137.45 -------------------

Main Client

Main Client

In this, Main Clients are created and then connected to the P2P server. P2P server will contains the IP addresses of connected main clients. If the client will get offline then its IP address wil be remove from P2P sever GUI.

Page | 39

.3

Creating Miniserver and Miniclient on Peer to Peer

Connection with Mini Client Main Server P2P SERVER (MAIN) Mini Server Channel for getting

Response from sever

MINI CLIENT - Basically for Connecting Two Another Peers. MINI SERVER - Service for other Peers to Connect.

In this module, we have P2P Main Client and P2P Main Server. Every client is itself a mini client and mini server. In mini server there is one miniserver request handler which will use the DataOutput Stream & DataInput Stream.It will help us in searching and downloading the file from other peer.

Page | 40

.4

Manage Online or Offline user list in Real Time

Connected
192.168.137.21

192.168.137.21

Connected
192.168.137.78

192.168.137.78 -------------------------------------

Not Connected
192.168.137.99

In this module, P2P Main Server contains the list of IP addresses of connected users.P2P server will show the names of the user which are online and connected to the main server & does not contain the names of those user which are offline.

Page | 41

.5

Sharing Files on P2P Network

1.mp3 2.jpg 2.exe

192.168.137.21 192.168.137.78 -------------------------------------

P2P Main Client

P2P Main Server

P2P or Peer-to-peer file sharing allows users to download media files such as music, movies, and games using a P2P software client that searches for other connected computers. The only requirements for a computer to join peer-to-peer networks are an Internet connection and P2P software.

Page | 42

.6

Receive search Request on Server Side

Send search request for any file
192.168.137.21

(like 1.mp3) Online Systems
192.168.137.21

192.168.137.21

192.168.137.78 -------------------------------------

Send search request for any file
192.168.137.21

(like 2.jpg)

P2P Main Server
In this, Client 1 send search request for any file that he /she wants like one.mp3, two.jpg etc. to the P2P main server.

Page | 43

.7

Search file on Peers and sending Result back

1)
192.168.137.21

1.) Search 1.mp3 4.) Send list of clients having the file Online Systems 2.) Do You have 1.mp3
192.168.137.78 192.168.137.21 192.168.137.78

Yes ------>

-------------------------------------

3.) Do You have 1.mp3
192.168.137.99

No ------->

In this, Client 1 searches for the file like one.mp3 from P2P main server and in response P2P main server sends list of clients having the file. If the other client will not have the file then message “File not found” will be shown on the side of requesting peer. If the peer have that specified copy or other related file ,then the files will be displayed on the Jtable.

Page | 44

.8

Downloading File from other peer

MAIN CLIENT Connected to mini server MINI CLIENT

MAIN CLIENT

Downloading file from other peer through Mini server

MINI CLIENT

Downloading file from one peer

Uploading file to other peer

P2P MAIN Connected SERVER Connected

Now Client 1 has the list of peers having searched file. Then Client 1 will get connected to mini server. Client can download file from other peer through mini server. Mini Server will upload file to other peer. The peer will select the file he/she need and start downloading it.If that file is already existing in their shared folder , miniserver will ask them “file already exist “ do you want to download it and rename it”

Page | 45

.9

Peers can chat and ask other peers to share files

Send text ( ask for file ) Main Client 1 Connected Send text ( chat text ) Main Client 2

P2P MAIN SERVER

To chat we have two clients Client 1 and Client 2 and they are connected to each other. Client 1 send text(ask for file), in response Client 2 send text(chat text file).Client1& Client 2 are connected to P2P server. In this module we will create a TextArea in our mainclient form .The text of textfield will be move to the selected IP and it will be displayed on other IP textfield.

Page | 46

CHAPTER 11

DESIGN

Page | 47

11.1 DESIGN PHASE
In systems, design functions and operations are described in detail, including screen layouts, business rules, process diagrams and other documentation. The output of this stage will describe the new system as a collection of modules or subsystems. The design stage takes as its initial input the requirements identified in the approved requirements document. For each requirement, a set of one or more design elements will be produced as a result of interviews, workshops, and/or prototype efforts. Design elements describe the desired software features in detail, and generally include functional hierarchy diagrams, screen layout diagrams, tables of business rules, business process diagrams, pseudo code, and a complete entity-relationship diagram with a full data dictionary. These design elements are intended to describe the software in sufficient detail that skilled programmers may develop the software with minimal additional input.

Requirements Document

DESIGN STAGE

Design Document

Updated Project Plan & Schedule

Updated Requirements Traceability Matrix

Figure 11.1 : Design Phase
Page | 48

CHAPTER 12

DATA FLOW DIAGRAMS

Page | 49

12.1 INTRODUCTION
A data-flow diagram (DFD) is a graphical representation of the "flow" of data through an information system. DFDs can also be used for the visualization of data processing. On a DFD, data items flow from an external data source or an internal data store to an internal data store or an external data sink, via an internal process.A DFD provides no information about the timing or ordering of processes, or about whether processes will operate in sequence or in parallel. It is common practice to draw a context-level data flow diagram first, which shows the interaction between the system and external agents which act as data sources and data sinks. On the context diagram (also known as the Level 0 DFD) the system's interactions with the outside world are modeled purely in terms of data flows across the system boundary. The context diagram shows the entire system as a single process, and gives no clues as to its internal organization. This context-level DFD is next "exploded", to produce a Level 1 DFD that shows some of the detail of the system being modeled. The Level 1 DFD shows how the system is divided into subsystems, each of which deals with one or more of the data flows to or from an external agent, and which together provide all of the functionality of the system as a whole. It also identifies internal data stores that must be present in order for the system to do its job, and shows the flow of data between the various parts of the system.

Figure 12.1: Data-flow diagram notation

Page | 50

Data Flow Diagrams (DFD)
12.2 Level 0 - Basic Working

CLIENT 2

CLIENT 1 STUDY OF PROPOSED SYSTEM Downloading
Search Files Shared  Most of the existing systems poss. Our system shall give the user

CLIENT n

 System requirement of our software is pretty low. Shared  System performance of our software will be pretty high then other exiting systemsDownloading due to Files Files multithreading feature of java. P2P MAIN  Our system is platform independent.

SERVER

 Downloading speed is much better as our system works in TCP/IP network.

Page | 51

12.3 Level 1- Get List of Online Clients from Main Server

Get List of Online Clients

CONNECTION TO

CLIENT
IP of Online Clients

MAIN SERVER

GET IP

12.4 Sharing Files By Clients

CLIENT 1

CONNECT TO MINISERVE

SELECT FILES

SHARE FILES

Page | 52

12.5 Downloading Files By Client From Other Peers

Broadcast Search

CLIENT 2

Search Results Search String

CLIENT 1

MINI SERVER

Joined Search Results Broadcast Search

SELECT FILE FROM SEARCH

Search Results

CLIENT n

DOWNLOAD

Page | 53

CHAPTER 13

13.1 CLASS DIAGRAM OF MAIN SERVER

P2P SERVER

P2P SERVER GUI

CLIENT HANDLER

Page | 54

13.2 CLASS DIAGRAM OF CLIENT

CLIENT

MINI SERVER

MINI SERVER REQUEST HANDLER

MINI CLIENT

SHARED PATH

CLIENT GUI
PEER INFO

HISTORY1

TEST SPEED

TESTING
Page | 55

CHAPTER 14

GANTT CHART

TIME TASK

Duration (in days)
DEC
JAN FEB MAR APR

Technology Training Project Initialization
Requirement Gathering

Analysis System Design Coding Unit Testing Integration Testing System Testing Implementation

Figure 14.1: Gantt Chart of the Project Point-to-Point sharing System

Page | 56

CHAPTER 15

SNAPSHOTS & CODING

Page | 57

15.1 Welcome Screen

Page | 58

15.2 Peer2Peer Main Server

On the Click of Start Button List of Online Peers will be display on server.

Page | 59

Before Client get online he has to enter the IP address of Server

If SharedPath Document Doesnot Exist

If Download History Document Doesnot Exist

Page | 60

If Shared Folder Doesnot exist in C Drive

Shared Folder In C Drive

Page | 61

15.4 CLIENT GUI

If Client is not able to connect to server on click of start button

Page | 62

On Click of Getlist Button One Peer will get the list of other Online Peers

If Main Server is not Running

Page | 63

Search Without getting the list of Online Client

Searching files from peers after getting online clients

Page | 64

Searching Without entering the text

If File Search by the peer will not found

Page | 65

15.6 To Download the File

Page | 66

15.6.1 To Open the Downloaded File

Page | 67

15.6.2 The Downloaded File will get Stored in Shared Folder

15.6.3 To Download Already Existing File

Page | 68

15.6.4 To Rename The File

To Rename The Existing File

Page | 69

Downloading Complete

To Open downloaded File

Page | 70

15.7 Changing the Shared Path by Peers

Page | 71

To Change the Shared Path

Page | 72

To Save the Path

Page | 73

15.8 Testing the Speed of other peers so that one can decide from which peer he can download the file in less time and faster.

Page | 74

To Check the Link Speed

Checking Link Speed

Page | 75

One can view others peers who are downloading files from his/her computer

Page | 76

15.9 To View Attached Peers

Page | 77

15.10 One can view the download history

Page | 78

Download History

Page | 79

15.11 If someone wants to cancel the downlaoding from other peer.

Page | 80

While Downlaoding File

On Click Of Cancel Downlaod

Page | 81

Downloading Cancelled

After The Downlaod is Cancelled

Page | 82

15.12 To Send Message or chating with other peer

Page | 83

To send message without selecting any IP Address

Page | 84

Message Send From one peer : 198.168.137.44

Message Received By Other Peer :198.168.137.43

Page | 85

15.13 Changing Themes according to user choice

Page | 86

Peacock Theme

Amazing Cyan theme

Page | 87

import com.sun.org.apache.bcel.internal.generic.BREAKPOINT; import java.awt.Button; import java.awt.Component; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseListener; import javax.swing.table.AbstractTableModel; import java.util.*; import java.net.*; import java.io.*; import java.text.DecimalFormat; import javax.swing.JOptionPane; import java.util.Date; import java.util.Calendar; import java.text.SimpleDateFormat; import java.util.ArrayList; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; public class clientGUI extends javax.swing.JFrame {
Page | 88

ServerSocket sersock; ArrayList<String> al = new ArrayList<String>(); tablemodel tm; JLabel lb ; String speed3; ArrayList<SearchFiles> files = new ArrayList<SearchFiles>(); tablemodel1 tm1; String msg = ""; ArrayList<speed> sp1 = new ArrayList<speed>(); ArrayList<SearchFiles> upc = new ArrayList<SearchFiles>(); ArrayList<history> his=new ArrayList<history>(); tablemodel3 tm3 = new tablemodel3(); boolean searchRequest = false; boolean downloadRequest = false; boolean canceldownload=false; boolean test=false; boolean testDownloadingSpeed=false; boolean progressbar=false; client cl; miniclient mc; miniserver ms = new miniserver(); FileReader fr1; BufferedReader br1; String sharedpath;
Page | 89

searchpath sp; Socket sc4; String ip; String fileToDownload = ""; Long per; testspeed ts; tablemodel4 tm4 ; tablemodel5 tm5=new tablemodel5(); boolean view=false; boolean getlist=false; boolean MessageRequest=false; String text="c:\\shared"; public clientGUI( ) { Try { ip= JOptionPane.showInputDialog("enter the ip address of server"); if(ip!=null) { File f = new File("c:\\shared"); File f3=new File("e:\\download_history.txt"); File f4=new File("e:\\sharedpath.txt"); File test = new File("c:\\shared\\test1.exe"); int count3=0;
Page | 90

if (!(f.exists())) { JOptionPane.showMessageDialog(null, "folder shared doesnot not exist...so create it first"); f.mkdir(); } if(!(f3.exists())) { JOptionPane.showMessageDialog(null, "text document download history doesnot not exist...so create it first"); f3.createNewFile(); } if(!(f4.exists())) { JOptionPane.showMessageDialog(null, "sharedpath document doesnot not exist...so create it first"); f4.createNewFile(); BufferedWriter output = new BufferedWriter(new FileWriter(f4)); output.write(text); output.close(); } fr1 = new FileReader("e:\\sharedpath.txt"); br1 = new BufferedReader(fr1); sharedpath = br1.readLine(); fr1.close(); FileOutputStream test1= new FileOutputStream(test);
Page | 91

byte b[]=new byte[50*1024*1024]; test1.write(b); System.out.println("MY SHARED FOLDER IS : " + sharedpath); tm = new tablemodel(); tm1 = new tablemodel1(); initComponents(); jTable2.getColumnModel().getColumn(0).setCellRenderer(new CellModel()); setSize(1000, 800); setVisible(true); jpbar.setVisible(false); jLabeldw.setVisible(false); jLabel5.setVisible(false); jEditorPane1.setContentType("text/html"); FileReader fd=new FileReader("e:\\download_history.txt"); BufferedReader br3=new BufferedReader(fd); String filed; String sized; String ip2; String date2; while(true) { String fs=br3.readLine(); if(fs==null || fs.equals("")) {
Page | 92

break; } StringTokenizer sfs= new StringTokenizer(fs,";"); filed=sfs.nextToken(); ip2=sfs.nextToken(); sized=sfs.nextToken(); date2=sfs.nextToken(); his.add(new history(filed,ip2,sized,date2)); } tm5.fireTableDataChanged(); } catch (Exception ex) { JOptionPane.showMessageDialog(null, "Cannot connect to server"); } } bt.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btActionPerformed(evt); } }); getContentPane().add(bt); bt.setBounds(20, 60, 160, 40); jButton1.setFont(new java.awt.Font("Tahoma", 1, 12));
Page | 93

jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/5617537541701984404.png"))); // NOI18N jButton1.setText("Get List"); jButton1.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jButton1MouseClicked(evt); } }); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); getContentPane().add(jButton1); jButton1.setBounds(190, 60, 160, 40); getContentPane().add(j); j.setBounds(280, 280, 120, 0); jButton2.setFont(new java.awt.Font("Tahoma", 1, 12)); jButton2.setIcon(newjavax.swing.ImageIcon(getClass().getResource("/images/check.gif"))); // NOI18N jButton2.setText("Check Mini Server"); jButton2.addActionListener(new java.awt.event.ActionListener() {
Page | 94

public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); getContentPane().add(jButton2); jButton2.setBounds(20, 310, 180, 40); jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12)); jLabel1.setText("MINI SERVER STATUS : "); getContentPane().add(jLabel1); jLabel1.setBounds(210, 320, 190, 30); getContentPane().add(tfsearch); tfsearch.setBounds(390, 60, 240, 40); btsearch.setFont(new java.awt.Font("Tahoma", 1, 12)); btsearch.setIcon(newjavax.swing.ImageIcon(getClass().getResource("/images/search.png"))); // NOI18N btsearch.setText("Search"); btsearch.setMaximumSize(new java.awt.Dimension(131, 41)); btsearch.setMinimumSize(new java.awt.Dimension(131, 41)); btsearch.setPreferredSize(new java.awt.Dimension(131, 41)); btsearch.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btsearchMouseClicked(evt);
Page | 95

} }); btsearch.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btsearchActionPerformed(evt); } }); getContentPane().add(btsearch); btsearch.setBounds(640, 60, 150, 40); jTable2.setModel(tm1); jTable2.setRowHeight(35); jScrollPane2.setViewportView(jTable2); getContentPane().add(jScrollPane2); jScrollPane2.setBounds(390, 110, 580, 190); btpath.setFont(new java.awt.Font("Tahoma", 1, 12)); btpath.setIcon(newjavax.swing.ImageIcon(getClass().getResource("/images/1907449.png"))); // NOI18N btpath.setText("My shared path"); btpath.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btpathActionPerformed(evt);
Page | 96

}); getContentPane().add(jButton3); jButton3.setBounds(580, 310, 180, 40); btdh.setFont(new java.awt.Font("Tahoma", 1, 12)); btdh.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/h5.jpg"))); // NOI18N btdh.setText("Download History"); btdh.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btdhActionPerformed(evt); } }); getContentPane().add(btdh); btdh.setBounds(770, 360, 200, 40); themes.setFont(new java.awt.Font("Tahoma", 1, 12)); themes.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Select Theme", "Baby Blue", "Aqua Green", "Plain Brown", "Pink Passion", "Abstract Blue ", "Peacock", "Stunningl Blue", "Amazing Cyan ", "Crazy Flowers" })); themes.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { themesActionPerformed(evt); }
Page | 97

}); getContentPane().add(themes); themes.setBounds(800, 20, 170, 30); jButton4.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jButton4.setIcon(newjavax.swing.ImageIcon(getClass().getResource("/images/delete_over.png") )); // NOI18N jButton4.setText("Cancel Download"); jButton4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton4ActionPerformed(evt); } }); getContentPane().add(jButton4); jButton4.setBounds(770, 410, 200, 40); jLabel6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/abcd.jpg"))); getContentPane().add(jLabel6); jLabel6.setBounds(0, 0, 990, 720); pack(); }// </editor-fold>//GEN-END:initComponents private void btActionPerformed(java.awt.event.ActionEvent evt) {//GENFIRST:event_btActionPerformed cl = new client(ip); jLabel5.setVisible(true);
Page | 98

}//GEN-LAST:event_btActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GENFIRST:event_jButton1ActionPerformed

cl.pw.println("getlist"); cl.pw.flush(); }//GEN-LAST:event_jButton1ActionPerformed private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GENFIRST:event_jButton2ActionPerformed int n = jTable1.getSelectedRow(); if (n != -1) { miniclient mc = new miniclient(ip); } else { JOptionPane.showMessageDialog(null, "Select IP first !!!"); } }//GEN-LAST:event_jButton2ActionPerformed private void btsearchActionPerformed(java.awt.event.ActionEvent evt) {//GENFIRST:event_btsearchActionPerformed if(getlist==false) { JOptionPane.showMessageDialog(null,"first click the start & getlist button"); } searchRequest = true;
Page | 99

for (int i = 0; i < al.size(); i++) { clientGUI.miniclient obj = new clientGUI.miniclient(al.get(i)); } }//GEN-LAST:event_btsearchActionPerformed private void btpathActionPerformed(java.awt.event.ActionEvent evt) {//GENFIRST:event_btpathActionPerformed sp = new searchpath(this, sharedpath); }//GEN-LAST:event_btpathActionPerformed private void btdownloadActionPerformed(java.awt.event.ActionEvent evt) {//GENFIRST:event_btdownloadActionPerformed try { int p; p = jTable2.getSelectedRow(); progressbar=true; canceldownload=false; if (p == -1) { JOptionPane.showMessageDialog(this, "Please select an item from list before sending download request"); } else { jpbar.setString("0 %"); downloadRequest = true;
Page | 100

fileToDownload = files.get(p).filename; miniclient mc = new miniclient(files.get(p).ipAddress); } } catch (Exception ex) { JOptionPane.showMessageDialog(null, "Client is offline !!!"); } }//GEN-LAST:event_btdownloadActionPerformed private void btdownloadItemStateChanged(java.awt.event.ItemEvent evt) {//GENFIRST:event_btdownloadItemStateChanged // TODO add your handling code here: }//GEN-LAST:event_btdownloadItemStateChanged private void viewButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GENFIRST:event_viewButton3ActionPerformed peerinfo pinfo = new peerinfo(); }//GEN-LAST:event_viewButton3ActionPerformed private void btchatActionPerformed(java.awt.event.ActionEvent evt) {//GENFIRST:event_btchatActionPerformed try { MessageRequest = true; int m; m = jTable1.getSelectedRow(); if (m != -1) {
Page | 101

String ip = al.get(m); clientGUI.miniclient obj = new clientGUI.miniclient(ip); } else { JOptionPane.showMessageDialog(null, "Please select an IP Address before sending message"); MessageRequest = true; } } catch (Exception ex) { ex.printStackTrace(); } }//GEN-LAST:event_btchatActionPerformed private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GENFIRST:event_jButton3ActionPerformed sp1.clear(); System.out.println("link speed object to be created"); testspeed ts=new testspeed(); }//GEN-LAST:event_jButton3ActionPerformed private void btdhActionPerformed(java.awt.event.ActionEvent evt) {//GENFIRST:event_btdhActionPerformed history1 h1=new history1(); }//GEN-LAST:event_btdhActionPerformed private void themesActionPerformed(java.awt.event.ActionEvent evt) {//GENFIRST:event_themesActionPerformed
Page | 102

int m; m=jTable2.getSelectedRow(); if (m == -1) { JOptionPane.showMessageDialog(this, " Start download first"); } else { int p=JOptionPane.showConfirmDialog(this, "Are you sure to cancel download", "cancel download",JOptionPane.OK_CANCEL_OPTION); if(p==JOptionPane.YES_OPTION) { progressbar=false; jpbar.setValue(0); jpbar.setVisible(false); jLabeldw.setVisible(false); canceldownload=true; JOptionPane.showMessageDialog(null, "Downloading is cancelled"); } if(p==JOptionPane.NO_OPTION) { canceldownload=false; } } } catch(Exception ex)
Page | 103

{ ex.printStackTrace(); } }//GEN-LAST:event_jButton4ActionPerformed public class client implements Runnable { Socket sock; Thread t1; BufferedReader brn, brk; PrintWriter pw; Thread t; String s; client(String ip) { Try { sock = new Socket(ip, 9000); brn = new BufferedReader(new InputStreamReader(sock.getInputStream())); pw = new PrintWriter(sock.getOutputStream()); brk = new BufferedReader(new InputStreamReader(System.in)); t = new Thread(this); t.start(); } catch (Exception e)
Page | 104

{ JOptionPane.showMessageDialog(null,"Cannot connected to server"); } } public void run() { try { while (true) { s = brn.readLine(); if (s.startsWith("SIZE")) { al.clear(); StringTokenizer st = new StringTokenizer(s); st.nextToken(); int size = Integer.parseInt(st.nextToken()); for (int i = 0; i < size; i++) { al.add(brn.readLine()); tm.fireTableDataChanged(); } } }
Page | 105

catch (Exception ex) { JOptionPane.showMessageDialog(null,"Main Server Is Not Running"); ex.printStackTrace(); } } } class tablemodel extends AbstractTableModel { String columns[] = {"IP Address"}; public String getColumnName(int c) { return (columns[c]); } Class columnstype[] = {String.class}; public Class getColumnClass(int i) { return columnstype[i]; } public int getColumnCount() { return 1; } public int getRowCount()
Page | 106

{ }

return al.size();

public Object getValueAt(int rowIndex, int columnIndex) { return al.get(rowIndex); } } class tablemodel1 extends AbstractTableModel { String title[] = {"FILE NAME", "IP ADDRESS", "FILE SIZE"}; @Override public String getColumnName(int m) { return title[m]; } public int getRowCount() { return files.size(); } public int getColumnCount() { return title.length; } public Object getValueAt(int rowIndex, int columnIndex) { if (columnIndex == 0) { return files.get(rowIndex).filename; } else if (columnIndex == 1) { return files.get(rowIndex).ipAddress; } else {
Page | 107

return files.get(rowIndex).filesizekb; } } } class CellModel extends DefaultTableCellRenderer { JLabel lb = new JLabel(); ImageIcon icon; @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { if (column == 0) { if (files.get(row).filename.endsWith(".jpg")) { icon = new ImageIcon(getClass().getResource("/images/jpg.png")); } else if (files.get(row).filename.endsWith(".exe")) { icon = new ImageIcon(getClass().getResource("/images/j.jpeg")); } else if (files.get(row).filename.endsWith(".pdf")) { icon = new ImageIcon(getClass().getResource("/images/pdf_icon.png")); } else if (files.get(row).filename.endsWith(".mp3")) { icon = new ImageIcon(getClass().getResource("/images/mp3.gif")); } else if (files.get(row).filename.endsWith(".doc")) { icon = new ImageIcon(getClass().getResource("/images/doc.png")); } else if (files.get(row).filename.endsWith(".mp4")) { icon = new ImageIcon(getClass().getResource("/images/mp4.gif")); } else if (files.get(row).filename.endsWith(".txt")) {
Page | 108

icon = new ImageIcon(getClass().getResource("/images/download.jpg")); } lb.setIcon(icon); lb.setText(files.get(row).filename); //lb.setOpaque(true); } else if (column == 1) { lb.setText(files.get(row).ipAddress); lb.setOpaque(true); } else { lb.setText(files.get(row).filesizekb); lb.setOpaque(true); } return lb; } } public class miniserver implements Runnable { Thread t1; Socket sc; miniserver() { t1 = new Thread(this); t1.start(); }
Page | 109

public void run() { try { sersock = new ServerSocket(9600); System.out.println("MiniServer started"); while (true) { sc = sersock.accept(); miniserver_requesthandler msrh = new miniserver_requesthandler(sc); System.out.println("Object of miniserver build"); } } catch (Exception ex) { ex.printStackTrace(); } } public class miniserver_requesthandler implements Runnable { Thread t2; Socket sc1; DataOutputStream dos; DataInputStream dis; String s;
Page | 110

miniserver_requesthandler(Socket sc1) { try { System.out.println("mini_server request handler constructor"); this.sc1 = sc1; dos = new DataOutputStream(this.sc1.getOutputStream()); dis = new DataInputStream(this.sc1.getInputStream()); t2 = new Thread(this); t2.start(); } catch (Exception ex) { ex.printStackTrace(); } } public void run() { try { String s3; System.out.println("In miniserver run mehtod"); s = dis.readLine(); System.out.println("Read first line in miniserver : " + s);
Page | 111

if (s.equals("check miniserver")) { dos.writeBytes("mini server is running\r\n"); dos.flush(); } String s1 = ""; while (true) { s1 = dis.readLine(); if(s1==null) break; System.out.println("Read second line : " + s1); if (s1.startsWith("search")) { StringTokenizer st = new StringTokenizer(s1, ","); st.nextToken(); String strToSearch = st.nextToken(); System.out.println("File to search is : " + strToSearch); File f = new File(sharedpath); String files[] = f.list(); System.out.println("Total files searched : " + files.length); int count = 0; for (int i = 0; i < files.length; i++) {
Page | 112

if (files[i].indexOf(strToSearch) != -1) { count++; } } dos.writeBytes("SIZE " + count + "\r\n"); dos.flush(); int i; if (count > 0) { for (i = 0; i < files.length; i++) { if (files[i].indexOf(strToSearch) != -1) { dos.writeBytes(files[i] + "\r\n"); dos.flush(); File file2 = new File(sharedpath + "\\" + files[i]); long fileSize = file2.length(); dos.writeLong(fileSize); dos.flush(); } } } break;
Page | 113

} else if (s1.startsWith("download")) { FileInputStream fis; System.out.println("In download block"); Try { int r; StringTokenizer str2 = new StringTokenizer(s1, ","); str2.nextToken(); String strdw = str2.nextToken(); long size1; String read; long size; System.out.println("Request at miniserver : " + strdw); if(strdw.equals("test1.exe")) { File test=new File("c:\\shared\\test1.exe"); fis = new FileInputStream(test); size=test.length(); dos.writeLong(size); } else {
Page | 114

File f = new File(sharedpath + "\\" + strdw); size = f.length(); fis = new FileInputStream(f); dos.writeLong(size); dos.flush(); } if(size<1024) { read=size+"bytes"; } else if(size<1048576) { read =(float) (size / 1024)+ "kb"; } else if(size<1024*1024*1024) { read = (int) (size / 1024*1024)+"mb"; } else { read = (float) (size / 1024*1024*1024)+"gb"; } upc.add(new SearchFiles(strdw, sc.getInetAddress().getHostAddress(), read )); tm3.fireTableDataChanged();
Page | 115

byte b[] = new byte[1024 * 1024]; long count = 0; while (true) { r = fis.read(b, 0, 1024 * 1024); dos.write(b, 0, r); dos.flush(); count = count + r; if (count == size) { break; } } fis.close(); System.out.println("File send "); for (int i = 0; i < upc.size(); i++) { if ((upc.get(i).filename).equals(strdw)) { upc.remove(i); tm3.fireTableDataChanged(); break; } }
Page | 116

} catch (Exception ex) { ex.printStackTrace(); } break; } else if (s1.startsWith("sending message from,")) { StringTokenizer mp = new StringTokenizer(s1, ","); mp.nextToken(); msg = msg + "<h3 color=\"blue\">Message from</h3>" + sc1.getInetAddress().getHostAddress() + "\n" + mp.nextToken() + "\n\n"; jEditorPane1.setText(msg); } } } catch (Exception ex) { ex.printStackTrace(); } } } } public class miniclient implements Runnable
Page | 117

{ Socket sc3; Socket sc4; PrintWriter pw1; DataInputStream dis; DataOutputStream dos; Thread t; String ip; int index; long flength; double speed1; FileWriter fw; String history; miniclient(String ip) { try { this.ip = ip; sc3 = new Socket(this.ip, 9600); System.out.println("Connection build with miniserver..."); dis = new DataInputStream(sc3.getInputStream()); dos = new DataOutputStream(sc3.getOutputStream()); dos.writeBytes("check miniserver\r\n"); dos.flush(); t = new Thread(this); t.start();
Page | 118

} catch (Exception ex) { ex.printStackTrace(); } } public void run() { if(progressbar==true) { jpbar.setBackground(Color.WHITE); jpbar.setForeground(Color.BLUE); jpbar.setStringPainted(true); } boolean b1 = true; try { long start = System.currentTimeMillis(); System.out.println(start); String s = dis.readLine(); if (s.equals("mini server is running")) { jLabel1.setText("MINI SERVER IS RUNNING"); } if (searchRequest == true) { files.clear();
Page | 119

String str = tfsearch.getText().trim(); if (str.equals("") || str == null) { JOptionPane.showMessageDialog(null, "Write proper string first"); } else { dos.writeBytes("search," + str + "\r\n"); dos.flush(); String res = dis.readLine(); { StringTokenizer st = new StringTokenizer(res); st.nextToken(); int size = Integer.parseInt(st.nextToken()); if (size == 0) { System.out.println("not found"); JOptionPane.showMessageDialog(null, "File not found!!"); } else { for (int i = 0; i < size; i++) { String filename = dis.readLine();
Page | 120

flength = (dis.readLong()); if (flength >= 1024 && flength < 1024 * 1024) { flength = (long) (flength / 1024); files.add(new SearchFiles(filename, ip, flength + " KB") } else if (flength >= 1024 * 1024 && flength < 1024 * 1024 * 1024) { flength = (long) (flength / (1024 * 1024)); files.add(new SearchFiles(filename, ip, flength + " MB")); } else if (flength >= 1024 * 1024 * 1024 && flength < 1024 * 1024 * 1024 * 1024) { flength = (long) (flength / (1024 * 1024 * 1024)); files.add(new SearchFiles(filename, ip, flength + " GB")); } else { files.add(new SearchFiles(filename, ip, flength + " bytes")); } tm1.fireTableDataChanged(); } } }
Page | 121

} searchRequest = false; } if (downloadRequest == true) { jpbar.setVisible(true); jpbar.setValue(0); dos.writeBytes("download," + fileToDownload + "\r\n"); dos.flush(); long start1 = System.currentTimeMillis(); long size = dis.readLong(); byte b[] = new byte[1024 * 1024]; long count = 0; int r; int p; String m; SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:MM:SS"); Date date = new Date(); String d= dateFormat.format(date); p = jTable2.getSelectedRow(); FileOutputStream fos; fileToDownload = files.get(p).filename; String ipadd=files.get(p).ipAddress; int u = fileToDownload.lastIndexOf(".");
Page | 122

String ext = fileToDownload.substring(u); boolean flag1 = false; File f1 = new File(sharedpath +"\\"+fileToDownload); long dwnld; if (f1.exists()) //logic if same file already exists { int n; n = JOptionPane.showConfirmDialog(null, "do you want to download existing file", null, JOptionPane.YES_NO_OPTION); if (JOptionPane.NO_OPTION == n) { JOptionPane.showMessageDialog(null, "no we don't want to download"); } else if (JOptionPane.YES_OPTION == n) //downloading Logic to replace file { int p1 = JOptionPane.showConfirmDialog(null, "do you want to rename the existing file", null, JOptionPane.YES_NO_OPTION); if (JOptionPane.YES_OPTION == p1) { String name = JOptionPane.showInputDialog("Rename", fileToDownload.substring(0, u)); if (name == null) { flag1 = true; } else { f1 = new File(sharedpath + "\\" + name + ext); } fos = new FileOutputStream(sharedpath + "\\" + name + ext);
Page | 123

while (true) { if(canceldownload==true) { break; } r = dis.read(b, 0, 1024 * 1024); count = count + r; fos.write(b, 0, r); dwnld = System.currentTimeMillis(); double diff = (dwnld - start) / 1000.0; double speed = count / diff; if(progressbar==true) {jpbar.setValue(0); per = (count * 100 / size); jpbar.setEnabled(downloadRequest); jpbar.setValue((int) (count * 100 / size)); jpbar.setString(per + "% complete"); jLabeldw.setVisible(true); if (speed <= 1024) { jLabeldw.setText("Speed is " + speed + "bps"); } if (speed > 1024 && speed <= 1024 * 1024) { jLabeldw.setText("Speed is " + (int) (speed / (1024)) + " kbps");
Page | 124

} if (speed > 1024 * 1024 && speed <= 1024 * 1024 * 1024) { jLabeldw.setText("Speed is " + (int) (speed / (1024 * 1024)) + " mbps"); } if (speed > 1024 * 1024 * 1024 && speed <= 1024 * 1024 * 1024 * 1024) { jLabeldw.setText("Speed is " + (int) (speed / (1024 * 1024 * 1024)) + " gbps"); } } if (count == size) { break; } } fos.close(); if(!canceldownload) { int a = JOptionPane.showConfirmDialog(null,"Open downloaded file ???"); if(a==JOptionPane.YES_OPTION) { System.out.println("explorer.exe "+sharedpath + "\\" + fileToDownload); Process p2 = Runtime.getRuntime().exec("explorer.exe "+sharedpath +"\\"+ fileToDownload); } jTable2.clearSelection(); FileWriter fw=new FileWriter("e:\\download_history.txt",true);
Page | 125

PrintWriter pw1 = new PrintWriter(fw); pw1.println(fileToDownload+";"+ipadd+";"+size+";"+date); pw1.flush(); his.add(newhistory(fileToDownload,ipadd,Long.toString(size),date.toString())); tm5.fireTableDataChanged(); }

if (JOptionPane.NO_OPTION == p1) { JOptionPane.showMessageDialog(null, "no we don't want to rename"); } } } } else //downloading logic for new file { fos = new FileOutputStream(sharedpath + "\\" + fileToDownload); while (true) { if (canceldownload==true) { break; } r = dis.read(b, 0, 1024 * 1024); count = count + r;
Page | 126

fos.write(b, 0, r); dwnld = System.currentTimeMillis(); double diff = (dwnld - start) / 1000; double speed = count / diff; if(progressbar==true) { per = (count * 100 / size); jpbar.setEnabled(downloadRequest); jpbar.setValue((int) (count * 100 / size)); jpbar.setString(per + "% complete"); jLabeldw.setVisible(true); double sp; String speed2; if (speed <1024) { sp=speed; DecimalFormat df=new DecimalFormat("0.00"); speed2=df.format(sp); speed3=speed2; jLabeldw.setText("Speed is " + speed3 + "bps"); } if (speed > 1024 && speed <= 1024 * 1024) { sp=(float)speed/1024; DecimalFormat df=new DecimalFormat("0.00"); speed2=df.format(sp);
Page | 127

speed3=speed2; jLabeldw.setText("Speed is " + speed3 + " kbps"); } if (speed > 1024 * 1024 && speed <= 1024 * 1024 * 1024) { sp=(float)speed/1024*1024; DecimalFormat df=new DecimalFormat("0.00"); speed2=df.format(sp); speed3=speed2; jLabeldw.setText("Speed is " + speed3 + " mbps"); } if (speed > 1024 * 1024 * 1024 && speed <= 1024 * 1024 * 1024 * 1024) { sp=(float)speed/1024*1024*1024; DecimalFormat df=new DecimalFormat("0.00"); speed2=df.format(sp); speed3=speed2; jLabeldw.setText("Speed is " + speed3 + " gbps"); } } if (count == size) { break; } } fos.close(); if(!canceldownload)
Page | 128

{ int a = JOptionPane.showConfirmDialog(null,"Open downloaded file ???"); if(a==JOptionPane.YES_OPTION) { System.out.println("explorer.exe "+sharedpath + "\\" + fileToDownload); Process p1 = Runtime.getRuntime().exec("explorer.exe "+sharedpath +"\\"+ fileToDownload); } } jTable2.clearSelection(); FileWriter fw=new FileWriter("e:\\download_history.txt",true); PrintWriter pw1 = new PrintWriter(fw); pw1.println(fileToDownload+";"+ipadd+";"+size+";"+date); pw1.flush(); his.add(newhistory(fileToDownload,ipadd,Long.toString(size),date.toString())); tm5.fireTableDataChanged(); } } downloadRequest = false; if (MessageRequest == true) { dos.writeBytes("sending message from," + textboxchat.getText() + "\r\n"); dos.flush(); msg = msg + "\nMessage"+ "<h3 color=\"black\">" + textboxchat.getText() + "\n" + "</h3 ><h3 color=\"red\">sent to:</h3>" + ip + "\n";
Page | 129

jEditorPane1.setText(msg); textboxchat.setText(""); } MessageRequest = false; if(testDownloadingSpeed==true) { System.out.println("In test downloadspeed==true"); dos.writeBytes("download,test1.exe\r\n"); dos.flush(); File f= new File("e:\\test2.exe"); FileOutputStream fos= new FileOutputStream(f); byte b[] = new byte[1024*1024]; int r; long count=0; long size1 = dis.readLong(); long start1=new Date().getTime(); System.out.println(start1); while(true) { r=dis.read(b,0,1024*1024); System.out.println("Bytes received >>>>"); fos.write(b,0,r); count+=r; System.out.println(count+" "+size1);
Page | 130

if(count==size1) break; } fos.close(); long current1=new Date().getTime(); long sec=(current1-start1)/1000; long speed1=(50*1024*1024)/sec; Float sp; String speed2; String speed4; if(speed1>1024*1024&&speed1<1024*1024*1024) { sp=(float)speed1/1024*1024; jLabeldw.setText("Speed is " + sp + " mbps"); sp1.add(new speed(ip,(sp+"mbps"))); } tm4.fireTableDataChanged(); testDownloadingSpeed=false; } if(view==true) { int u1 = fileToDownload.lastIndexOf("."); String name1=fileToDownload.substring(0,u1); String ext1 = fileToDownload.substring(u1);
Page | 131

if(ext1.equals("jpg")) { Process process = Runtime.getRuntime().exec("explorer.exe"+sharedpath+"\\"+fileToDownload); view=false; } } } catch (Exception ex) { ex.printStackTrace(); } } } public class peerinfo extends JFrame { JTable jtable3; JPanel jp; JScrollPane jsp; JLabel j2; JLabel jl; peerinfo() { jp = new JPanel(); jp.setSize(1000, 800); j2 = new JLabel(); jp.add(j2); j3 = new JLabel();
Page | 132

j4 = new JLabel(); j2.setFont(new java.awt.Font("Serif", 3, 48)); j2.setText("Connected Peers"); jp.add(j3); j3.setFont(new java.awt.Font("Tahoma", 1, 18)); j3.setText("Downloading Clients :"); j3.setBounds(120, 50, 400, 150); jl = new JLabel(); jl.setSize(1000, 700); jp.add(j4); j4.setBounds(600, 150, 300, 300); j4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/peers.png"))); j2.setBounds(350, 2, 440, 100); tm3 = new tablemodel3(); jtable3 = new JTable(tm3); jp.setLayout(null); jsp = new JScrollPane(jtable3); jsp.setBounds(100, 150, 400, 370); jp.add(jsp); add(jp); jp.add(jl); jl.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/solid-babyblue.jpg"))); setVisible(true); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
Page | 133

setSize(1000, 800); tm3.fireTableDataChanged(); } } public class testspeed extends JFrame implements ActionListener { JTable jtable4; JPanel jp1; JButton bt; JLabel tl; JScrollPane jsp1; ArrayList<speed> sp1 = new ArrayList<speed>(); JLabel pic; JLabel lb; JLabel back; JLabel head; testspeed() { back=new JLabel(); back.setSize(1000, 700); jp1 = new JPanel(); jp1.setSize(1000, 800); head=new JLabel(); head.setFont(new java.awt.Font("Serif", 3, 48));
Page | 134

head.setText("Speed Testing"); jp1.add(head); head.setBounds(300, 2, 440, 100); jp1.setLayout(null); bt=new JButton(); jp1.add(bt); bt.setSize(150, 30); bt.setBounds(220, 560, 160, 40); bt.setText("Check Link Speed"); pic=new JLabel(); pic.setBounds(530, 160, 430, 350); pic.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/Animated_Aston_Martin_Speedometer _1.gif"))); jp1.add(pic); bt.addActionListener( this); tl=new JLabel(); lb=new JLabel(); jp1.add(tl); jp1.add(lb); tl.setBounds(220,600,250,40); tl.setVisible(false); lb.setVisible(false); tm4 = new tablemodel4(); jtable4 = new JTable(tm4);
Page | 135

lb.setFont(new java.awt.Font("Serif", 3, 18)); lb.setText("Checking link speed...please wait !!!!!!"); lb.setBounds(100,550,400,90); lb.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/3d.gif"))); jsp1 = new JScrollPane(jtable4); jsp1.setBounds(100, 150, 400, 370); jp1.add(jsp1); add(jp1); jp1.add(back); back.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/solid-babyblue.jpg"))); setVisible(true); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setSize(1000, 800); }

class testing implements Runnable { Thread y; testing() { y=new Thread(this); y.start(); } public void run()
Page | 136

{ int countn=0; try { InetAddress addr=InetAddress.getLocalHost(); String b=addr.getHostAddress(); System.out.println("my address"+b); for(int u=0;u<al.size();u++) { if(al.get(u).equals(b)) { continue; } else { testDownloadingSpeed=true; miniclient on=new miniclient(al.get(u)); System.out.println("object created"+ ++countn); on.t.join(); } } } catch(Exception r) {
Page | 137

r.printStackTrace(); } } } public class history1 extends JFrame { JTable jt5; JPanel jp2; JScrollPane jsp1; JLabel j1; JLabel back; JLabel pic; history1() { jp2 = new JPanel(); back=new JLabel(); back.setSize(1000, 700); jp2.setSize(1000, 800); jp2.setLayout(null); jt5=new JTable(); tm5=new tablemodel5(); jt5 = new JTable(tm5); j1=new JLabel(); j1.setFont(new java.awt.Font("Serif", 3, 48));
Page | 138

j1.setText("Download History"); j1.setBounds(350, 2, 440, 100); pic=new JLabel(); pic.setBounds(550, 180, 400, 350); pic.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/hist.png"))); jp2.add(pic); jsp1 = new JScrollPane(jt5); jsp1.setBounds(100, 150, 400, 370); jp2.add(jsp1); add(jp2); jp2.add(j1); jp2.add(back); back.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/solid-babyblue.jpg"))); setVisible(true); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setSize(1000, 800); tm5.fireTableDataChanged(); } } class tablemodel3 extends AbstractTableModel { String title[] = {"File Name", "IP Address", "File Size"}; public int getRowCount() {
Page | 139

return upc.size(); } public int getColumnCount() { return 3; } @Override public String getColumnName(int m) { return title[m]; } public Object getValueAt(int rowIndex, int columnIndex) { if (columnIndex == 0) { return upc.get(rowIndex).filename; } else if (columnIndex == 1) { return upc.get(rowIndex).ipAddress; } else { return upc.get(rowIndex).filesizekb;
Page | 140

} } } public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new clientGUI().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton bt; private javax.swing.JButton btchat; private javax.swing.JButton btdh; private javax.swing.JButton btdownload; private javax.swing.JTable jTable1; private javax.swing.JTable jTable2; private javax.swing.JProgressBar jpbar; private javax.swing.JTextField textboxchat; private javax.swing.JTextField tfsearch; private javax.swing.JComboBox t
Page | 141

CHAPTER 12 FUTURE & FURTHER ENHANCEMENT OF PROJECT

Page | 142

FUTURE OF PROJECT
 Resuming Broken Downloads
When downloading large files, the download can break or be Interrupted. This means that you need to start all over to download it, which can be a real hassle for large files, or slow connections. When we will download the files in parts, it will reduce traffic congestion on network.

Virus Scanning of files before they are downloaded
If you frequently download files from suspicious peers, it’s probably worth it to check for viruses Before you download, instead of waiting to see if your regular anti-virus software will catch it after you download.

Video Conferencing And Audio Casting
The impact of video and audio web sites on the Internet has been very large over the last couple of years - and will only increase. Therefore there has been talk of moving video streaming to P2P networks, to lessen the load on the Internet. A P2P approach for video streaming would be to hold a copy of a file in different parts of the world and serve it from multiple points to users.

Mobile P2P Applications
Many popular web applications have been ported to mobile platforms already. Likewise there is huge potential for P2P mobile applications, at least when wireless network enabled mobile phones become more popular. I think it will follow the same trend as for PC P2P applications - i.e. it will start from instant messaging, followed by file-sharing and IP telephony, then video and other media.

 E-commerce
Consumer to Consumer e-commerce is one of the most popular services on the Internet. A centralized trading platform (such as eBay) enables consumers to trade, buy or sell their goods. However in a centralized system, there is always a possibility of a failure - such as the server goes down or is busy. P2P enabled e-commerce can remove the centralized system and so lessen the possibility of failures. However there are many things that have to be implemented for a P2P system for e-commerce to work - it has to be secure, transactional and workflow-based to track different stages of the sales process

Page | 143

CHAPTER 12
Appendix
Abstraction: Abstraction allows us to layer semantics of complex system, breaking them into more manageable pieces. API Package: Application Programming Interface: API contains a large number of packages which offers a different way to look at and handles certain I/O operation. AWT: Abstract Window Toolkit: It examines the standard controls and layout managers defined by JAVA. Bytecode: Bytecode is a highly optimized set of instructions designed to be executed by the java run time system. CSS: Cascading Style Sheets is a style sheet language used to describe the presentation semantics (that is, the look and formatting) of a document written in a markup language. Its most common application is to style web pages written in HTML and XHTML, but the language can be applied to any kind of XMLdocument, including SVG and XUL. Constraints : Any condition that limits the solutions to a problem. Console: It refers to that portion of a computer which is used for communication between operation or maintenance engineers and the computer mostly with the help of displays and manual controls. Encapsulation: Encapsulation is the mechanism that binds together code and data it manipulates, and keeps both safe from outside interference and misuse. Errors: An error is abnormal condition that arises in a code sequence at execution time. Exception: An exception is abnormal condition that arises in a code sequence at error time. Frontend: The part of project which is responsible for collecting input in various forms from the user and to processing it to conform to a specification the backend can use. Javax.swing : A java toolkit for developing graphical user interfaces (GUI) it includes elements such as menus, toolbar, and dialogue boxes. Java.io: It contains classes that are stream oriented and support input and output.

Page | 144

Java.awt.event : Provides interfaces and classes for dealing with different types events fired by awt components. Java.sql : provides the API for accessing and processing data stored in a data source using the java programming language. Java.util : It contains the collection framework, legacy collection classes, event model, date and time facilities, and internationalization utility classes. JDK : Java Development Kit: It is a basically a software development kit which is use to write and run java programs. JDBC : Java Data Base Compiler: It provides a standard interface for accessing a relational. It contains a set of classes and methods for issuing SQL statements, table updates, and calls to stored procedures. JRE : Java Runtime Environment: Is software which is required to run java applications interpretively on a target hardware and operating system platform. JVM : Java Virtual Machine: JVM is an interpreter for Bytecode. It provides the hardware platform specifications to which you compile all java technology code. URL : Uniform Resource locator: It is a unique address given to a particular web page. J2SE : Java 2 Standard Edition (Core Java). J2EE : Java 2 Enterprise Edition (Advanced Java).

Page | 145

CHAPTER 13 BIBLIOGRAPHY

Books
J2SE Notes -- VMM J2EE Notes –VMM Sun Microsystems: Java Programming Language Student Guide

Websites
 www.wikipedia.org  www.ebooks.com  www.google.com
Page | 146

(O-0)Abee(0-O)

Sign up to vote on this title
UsefulNot useful