Report
Report
PROJECT REPORT ON
Bachelor of Engineering In Computer Science Submitted By: Manali Gupta Priyanka Sharma Prateek Prakash Rahul D Raj
Under the Supervision of
DEPARTMENT OF COMPUTER SCIENCE & INFORMATION TECHNOLOGY INSTITUTE OF ENGINEERING & TECHNOLOGY, MANGALAYATAN UNIVERSITY, ALIGARH [2010 2011]
CERTIFICATE
This is to certify that the project entitled PHOENIX CHAT SERVER has been carried out by the team under my guidance in partial fulfillment of the degree of Bachelor of Engineering in Computer Engineering / Information Technology of Mangalayatan University, Aligarh during the academic year 2010-2011(Semester-VIII).
Team:
1. 2. 3. 4.
Guide
External Examiner:
ACKNOWLEDGEMENT
Before, we get into thick of things, we would like to add a few heartfelt words for all those people who were part of this report in numerous ways, and gave their unending support throughout. We wish to express our thanks and gratitude to all those who have provided the valuable support, insight and encouragement during our project work at Mangalayatan University. In the process of completing this project Phoenix Chat Server, we have received cooperation from many quarters. We express our sincere gratitude and indebtness to Mr. Vivek Agrawal, our project guide for his inspiring guidance, cooperation and for giving us an opportunity to enhance our skill and hence, carrying out our final year project successfully. We are thankful for his guidance, patience and consummate support. He came to our help when it counted and we extend our heartiest thanks to him for enlightening our path. Moreover, we would also like to acknowledge my profound sense of gratitude and indebtness for Mr. Vikas Solanki (H.O.D. Computer Science Department) for his cooperation, guidance, support and precious suggestions that motivated us in completing this project. We also feel grateful and elated in expressing our indebtedness to all those who have directly or indirectly helped us in accomplishing this research work.
PREFACE
The Purpose of this Project Report is to understand the basic steps of Analysis, Design, and Implementation in my project. I have tried to comprehend the parameters and dimensions of the project at this stage. I have made use of the object based approach. I have made use of basic concepts of language Java, networking and relational database to understand the flow of Project. As we amble through the document, I can construe the major modules in the system, their relationships with each other, flow of events and messages between them and to understand the function of each module at the different states of project.
CONTENTS
Page No. 1. Introduction About the project & its relevance JAVA Concepts Relational Database Overview 2. 3. 4. 5. System analysis Feasibility Analysis System Design System Requirement Hardware Requirements Software Requirements 6. Programming Approach Java o JFC o SWING o JAVA 2D Client & Server Architecture o Network Datagrams o Socket & Ports o Diagram Representation 7. Software Coding Chat Client GUI Chat Server GUI 8. 9. Snapshots Conclusions 92 101 68 59 29 31 33 36 7
10.
References
103
1.
General Concept of Chat Server:
INTRODUCTION
CHAT SERVER is an online system developed for the group of members to communicate with each other over the internet. This system solves almost all the limitations of the conventional system. Both the students and teachers and the company are equally benefited by the proposed system. The system saves a lot of time and effort for both. Chat Server is an application through which end users, by the use of Chat client applications at their respective ends, can chat indirectly. We are introducing new software called CHAT SERVER for chatting purpose. We can say thoroughly that this software is very useful for the college. It is mainly designed for the college to reduce the communication gap between the different peoples in a college.
JAVA CONCEPTS
JFC is short for Java Foundation Classes, which encompass a group of features for building graphical user interfaces (GUIs) and adding rich graphics functionality and interactivity to Java applications. It is defined as containing the features shown in the table below. Features of the Java Foundation Classes Feature Description Includes everything from buttons to split panes to tables. Many components are capable of sorting, printing, and drag and drop, to name a few of the supported features.
Swing Components
GUI
The look and feel of Swing applications is pluggable, allowing a choice of look and feel. For example, the same program can use either the Java or the Windows look and Pluggable Lookfeel. Additionally, the Java platform supports the GTK+ and-Feel Support look and feel, which makes hundreds of existing look and feels available to Swing programs. Many more look-andfeel packages are available from various sources. Enables assistive technologies, such as screen readers and Braille displays, to get information from the user interface. Enables developers to easily incorporate high-quality 2D graphics, text, and images in applications and applets. Java 2D includes extensive APIs for generating and sending high-quality output to printing devices.
Accessibility API
Java 2D API
Internationalization Allows developers to build applications that can interact with users worldwide in their own languages and cultural 9
conventions. With the input method framework developers can build applications that accept text in languages that use thousands of different characters, such as Japanese, Chinese, or Korean. This trail concentrates on the Swing components. We help you choose the appropriate components for your GUI, tell you how to use them, and give you the background information you need to use them effectively. We also discuss other JFC features as they apply to Swing components. Swing text components display text and optionally allow the user to edit the text. Programs needed text components for tasks ranging from the straightforward (enter a word and press Enter) to the complex (display and edit styled text with embedded images in an Asian language). Swing provides six text components, along with supporting classes and interfaces that meet even the most complex text requirements. In spite of their different uses and capabilities, all Swing text components inherit from the same superclass, Jcomponent which provides a highly-configurable and powerful foundation for text manipulation. The following figure shows the JTextComponent hierarchy.
10
JDBC Introduction:
The JDBC API is a Java API that can access any kind of tabular data, especially data stored in a Relational Database. JDBC helps you to write java applications that manage these three programming activities: 1. Connect to a data source, like a database 2. Send queries and update statements to the database 3. Retrieve and process the results received from the database in answer to your query. The following simple code fragment gives a simple example of these three steps: Connection con = DriverManager.getConnection ( "jdbc:myDriver:wombat", "myLogin","myPassword"); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM Table1"); while (rs.next()) { int x = rs.getInt("a"); String s = rs.getString("b"); float f = rs.getFloat("c"); } This short code fragment instantiates a DriverManager object to connect to a database driver and log into the database, instantiates a Statement object that carries your SQL language query to the database; instantiates a ResultSet object that retrieves the results of your query, and executes a simple while loop, which retrieves and displays those results. It's that simple. 11
12
corporate network where client installations are not a major problem, or for application server code written in Java in three-tier architecture. This Trail uses the first two of these four JDBC components to connect to a database and then build a java program that uses SQL commands to communicate with a test Relational Database. The last two components are used in specialized environments to test web applications, or to communicate with ODBC-aware DBMSs.
JDBC Architecture:
Two-tier and three-tier Processing Models The JDBC API supports both two-tier and three-tier processing models for database access.
Figure 1: Two-tier Architecture for Data Access.
In the two-tier model, a Java applet or application talks directly to the data source. This requires a JDBC driver that can communicate with the particular data source being accessed. A user's commands are delivered to the database or other data source, and the results of those statements are sent back to the user. The data source may be located on another machine to which the user is connected via a network. This is referred to as a client/server configuration, with the user's machine as the client, and the machine housing the data source as the server. The network can be an intranet, which, for example, connects employees within a corporation, or it can be the Internet. In the three-tier model, commands are sent to a "middle tier" of services, which then sends the commands to the data source. The data source processes the commands and sends the results back to the middle tier, which then sends them to the user. MIS directors find the three-tier model very attractive 13
because the middle tier makes it possible to maintain control over access and the kinds of updates that can be made to corporate data. Another advantage is that it simplifies the deployment of applications. Finally, in many cases, the three-tier architecture can provide performance advantages.
Figure 2: Three-tier Architecture for Data Access.
Until recently, the middle tier has often been written in languages such as C or C++, which offer fast performance. However, with the introduction of optimizing compilers that translate Java bytecode into efficient machinespecific code and technologies such as Enterprise JavaBeans, the Java platform is fast becoming the standard platform for middle-tier development. This is a big plus, making it possible to take advantage of Java's robustness, multithreading, and security features. With enterprises increasingly using the Java programming language for writing server code, the JDBC API is being used more and more in the middle tier of three-tier architecture. Some of the features that make JDBC a server technology are its support for connection pooling, distributed transactions, and disconnected row sets. The JDBC API is also what allows access to a data source from a Java middle tier.
14
A computer system normally has many active processes and threads. This is true even in systems that only have a single execution core, and thus only have one thread actually executing at any given moment. Processing time for a single core is shared among processes and threads through an OS feature called time slicing. It's becoming more and more common for computer systems to have multiple processors or processors with multiple execution cores. This greatly enhances a system's capacity for concurrent execution of processes and threads but concurrency is possible even on simple systems, without multiple processors or execution cores.
I/O STREAMS:
An I/O Stream represents an input source or an output destination. A stream can represent many different kinds of sources and destinations, including disk files, devices, other programs, and memory arrays. Streams support many different kinds of data, including simple bytes, primitive data types, localized characters, and objects. Some streams simply pass on data; others manipulate and transform the data in useful ways. No matter how they work internally, all streams present the same simple model to programs that use them: A stream is a sequence of data. A program uses an input stream to read data from a source, one item at a time:
STREAM
DATA SOURCE 0011010000 1001000011 1001010101 1001010101 PROGRAM
15
A program uses an output stream to write data to a destination, one item at time: STREAM
PROGRAM
Creating Streams:
Here is an example of how to create a stream that reads and writes characters using a TCP/IP socket as the sink and source. The classes themselves are explained later. 16
First, we create a TCP/IP socket object that is connected to www.ibm.com and port 80. This is the Web server port. The method getInputStream() in the Socket class returns an InputStream, which represents byte-by-byte reading of the socket. The InputStream is used to create an InputStreamReader, which transforms the bytes read from the socket into characters. A BufferedReader class is created which reads from the InputStreamReader and buffers the characters into its own internal buffer. The object named in then reads characters from that buffer, but the ultimate source of the characters is the Web server at www.ibm.com. On the other hand, the getOutputStream() method of the Socket class returns a reference to an OutputStream, which writes a byte at a time. The PrinterWriter constructor uses that OutputStream as the sink for the characters it writes out. When a character is written to the object named out, it is ultimately sent to the Web server atwww.ibm.com. This example treats the data stream as character data: Socket a_socket = new Socket (www.ibm.com, 80); InputStreamReader isr = new InputStreamReader (a_socket.getInputStream ());
17
Data I/O:
This section introduces data input and output: * DataInputStream * DataOutputStream Several classes implement the DataInput and DataOutput interfaces. Let's talk about how they work. The primitive data types, such as ints, may be represented differently on the various platforms that Java code runs on. For example, an int may be represented with the most significant byte first (called Big Endian), as on an IBM mainframe, or with the least significant byte first (called Little Endian), as on an IBM PC. If you wrote out an int in binary form with a C program on one platform and tried to read it in on the other platform, the values would not agree. That's where DataInput and DataOutput come in. Now you can take a primitive, like an int, and write it out. It is written in a platform-independent form. You can read that int back in on any other Java virtual machine and, regardless of where it was produced; it will be turned back into an int of the proper value. All the primitives, such as doubles, ints, shorts, longs, and so forth, can be written in a system platform-independent manner using the methods in DataOutput. Likewise, they can be read using the methods in DataInput.
18
19
Integrity Rules:
Relational tables follow certain integrity rules to ensure that the data they contain stay accurate and are always accessible. First, the rows in a relational table should all be distinct. If there are duplicate rows, there can be problems resolving which of two possible selections is the correct. For most DBMSs, the user can specify that duplicate rows are not allowed, and if that is done, the DBMS will prevent the addition of any rows that duplicate an existing row. A second integrity rule of the traditional relational model is that column values must not be repeating groups or arrays. A third aspect of data integrity involves the concept of a null value. A database takes care of situations where data may not be available by using a null value to indicate that a value is missing. It does not equate to a blank or zero. A blank is considered equal to another blank, a zero is equal to another zero, but two null values are not considered equal. When each row in a table is different, it is possible to use one or more columns to identify a particular row. This unique column or group of columns is called a primary key. Any column that is part of a primary key cannot be null; if it were, the primary key containing it would no longer be a complete identifier. This rule is referred to as entity integrity.
20
Table illustrates some of these relational database concepts. It has five columns and six rows, with each row representing a different employee. Table: Employees Employee_Number First_name Last_Name Date_of_Birth Car_Number 10001 10083 10120 10005 10099 10035 Axel Arvid Jonas Florence Sean Elizabeth Washington Sharma Ginsberg Wojokowski Washington Yamaguchi 28-Aug-43 24-Nov-54 01-Jan-69 04-Jul-71 21-Sep-66 24-Dec-59 5 null null 12 null null
The primary key for this table would generally be the employee number because each one is guaranteed to be different. (A number is also more efficient than a string for making comparisons.) It would also be possible to use First_Name and Last_Name because the combination of the two also identifies just one row in our sample database. Using the last name alone would not work because there are two employees with the last name of "Washington." In this particular case the first names are all different, so one could conceivably use that column as a primary key, but it is best to avoid using a column where duplicates could occur. If Elizabeth Taylor gets a job at this company and the primary key is First_Name, the RDBMS will not allow her name to be added (if it has been specified that no duplicates are permitted). Because there is already an Elizabeth in the table, adding a second one would make the primary key useless as a way of identifying just one row. Note that although using First_Name and Last_Name is a unique composite key for this example, it might not be unique in a larger database. Note also that Table 1.2 assumes that there can be only one car per employee.
21
SELECT Statements:
SQL is a language designed to be used with relational databases. There is a set of basic SQL commands that is considered standard and is used by all RDBMSs. For example, all RDBMSs use the SELECT statement. A SELECT statement, also called a query, is used to get information from a table. It specifies one or more column headings, one or more tables from which to select, and some criteria for selection. The RDBMS returns rows of the column entries that satisfy the stated requirements. A SELECT statement such as the following will fetch the first and last names of employees who have company cars: SELECT First_Name, Last_Name FROM Employees WHERE Car_Number IS NOT NULL The result set (the set of rows that satisfy the requirement of not having null in the Car_Number column) follows. The first name and last name are printed for each row that satisfies the requirement because the SELECT statement (the first line) specifies the columns First_Name and Last_Name. The FROM clause (the second line) gives the table from which the columns will be selected. FIRST_NAME -------------------Axel Florence LAST_NAME ------------------Washington Wojokowski
The following code produces a result set that includes the whole table because it asks for all of the columns in the table Employees with no restrictions (no WHERE clause). Note that SELECT * means "SELECT all columns." SELECT * FROM Employees
22
WHERE Clauses:
WHERE clause in SELECT statement provides the criteria for selecting values. For example, in the following code fragment, values will be selected only if they occur in a row in which the column Last_Name begins with the string 'Washington'. SELECT First_Name, Last_Name FROM Employees WHERE Last_Name LIKE 'Washington%' The keyword LIKE is used to compare strings, and it offers the feature that patterns containing wildcards can be used. For example, in the code fragment above, there is a percent sign (%) at the end of 'Washington', which signifies that any value containing the string 'Washington' plus zero or more additional characters will satisfy this selection criterion. So 'Washington' or 'Washingtonian' would be matches, but 'Washing' would not be. The other wildcard used in LIKE clauses is an underbar (_), which stands for any one character. For example, WHERE Last_Name LIKE 'Ba_man' would match 'Batman', 'Barman', 'Badman', 'Balman', 'Bagman', 'Bamman', and so on. The code fragment below has a WHERE clause that uses the equal sign (=) to compare numbers. It selects the first and last name of the employee who is assigned car 12. SELECT First_Name, Last_Name FROM Employees WHERE Car_Number = 12 The next code fragment selects the first and last names of employees whose employee number is greater than 10005: SELECT First_Name, Last_Name FROM Employees WHERE Employee_Number > 10005
23
WHERE clauses can get rather elaborate with multiple conditions and in some DBMSs or in nested conditions. This overview will not cover complicated WHERE clauses, but the following code fragment has a WHERE clause with two conditions; this query selects the first and last names of employees whose employee number is less than 10100 and who do not have a company car. SELECT First_Name, Last_Name FROM Employees WHERE Employee_Number < 10100 and Car_Number IS NULL
Joins:
A distinguishing feature of relational databases is that it is possible to get data from more than one table in what is called a join. Suppose that after retrieving the names of employees who have company cars, one wanted to find out who has which car, including the make, model, and year of car. This information is stored in another table, Cars, shown in Table 1.3. Table: Cars Car Number 5 12 Make Honda Toyota Model Civic DX Corolla Year 1996 1999
There must be one column that appears in both tables in order to relate them to each other. This column, which must be the primary key in one table, is called the foreign key in the other table. In this case, the column that appears in two tables is Car_Number, which is the primary key for the table Cars and the foreign key in the table Employees. If the 1996 Honda Civic were wrecked and deleted from the Cars table, then Car_Number 5 would also have to be removed from the Employees table in order to maintain what is called referential integrity. Otherwise, the foreign key column (Car_Number) in Employees would contain an entry that did not refer to anything in Cars. A foreign key must either be null or equal to an existing primary key value of the table to which it refers. This is different from a primary key, which may not be 24
null. There are several null values in the Car_Number column in the table Employees because it is possible for an employee not to have a company car. The following code asks for the first and last names of employees who have company cars and for the make, model, and year of those cars. Note that the FROM clause lists both Employees and Cars because the requested data is contained in both tables. Using the table name and a dot (.) before the column name indicates which table contains the column. SELECT Employees.First_Name, Employees.Last_Name, Cars.Make, Cars.Model, Cars.Year FROM Employees, Cars WHERE Employees.Car_Number = Cars.Car_Number This returns a result set that will look similar to the following: FIRST_NAME LAST_NAME ------------------- ------------------Axel Washington Florence Wojokowski MAKE MODEL YEAR --------------------- --------Honda CivicDX 1996 Toyota Corolla 1999
SELECT - used to query and display data from a database. The SELECT statement specifies which columns to include in the result set. The vast majority of the SQL commands used in applications are SELECT statements. INSERT - adds new rows to a table. INSERT is used to populate a newly created table or to add a new row (or rows) to an already-existing table. 25
DELETE - removes a specified row or set of rows from a table UPDATE - changes an existing value in a column or group of columns in a table
CREATE TABLE - creates a table with the column names the user provides. The user also needs to specify a type for the data in each column. Data types vary from one RDBMS to another, so a user might need to use metadata to establish the data types used by a particular database. CREATE TABLE is normally used less often than the data manipulation commands because a table is created only once, whereas adding or deleting rows or changing individual values generally occurs more frequently. DROP TABLE - deletes all rows and removes the table definition from the database. A JDBC API implementation is required to support the DROP TABLE command as specified by SQL92, Transitional Level. However, support for the CASCADE and RESTRICT options of DROP TABLE is optional. In addition, the behavior of DROP TABLE is implementationdefined when there are views or integrity constraints defined that reference the table being dropped. ALTER TABLE - adds or removes a column from a table. It also adds or drops table constraints and alters column attributes.
26
Earlier JDBC API versions added new capabilities for a result set's cursor, allowing it to move both forward and backward and also allowing it to move to a specified row or to a row whose position is relative to another row.
Transactions:
When one user is accessing data in a database, another user may be accessing the same data at the same time. If, for instance, the first user is updating some columns in a table at the same time the second user is selecting columns from that same table, it is possible for the second user to get partly old data and partly updated data. For this reason, DBMSs use transactions to maintain data in a consistent state (data consistency) while allowing more than one user to access a database at the same time (data concurrency). A transaction is a set of one or more SQL statements that make up a logical unit of work. A transaction ends with either a commit or a rollback, depending on whether there are any problems with data consistency or data concurrency. The commit statement makes permanent the changes resulting from the SQL statements in the transaction, and the rollback statement undoes all changes resulting from the SQL statements in the transaction. A lock is a mechanism that prohibits two transactions from manipulating the same data at the same time. For example, a table lock prevents a table from being dropped if there is an uncommitted transaction on that table. In some DBMSs, a table lock also locks all of the rows in a table. A row lock prevents two transactions from modifying the same row, or it prevents one transaction from selecting a row while another transaction is still modifying it.
Stored Procedures:
A stored procedure is a group of SQL statements that can be called by name. In other words, it is executable code, a mini-program that performs a particular task that can be invoked the same way one can call a function or method. Traditionally, stored procedures have been written in a DBMS-specific programming language. The latest generation of database products allows stored procedures to be written using the Java programming language and the JDBC API. Stored procedures written in the Java programming language are 27
bytecode portable between DBMSs. Once a stored procedure is written, it can be used and reused because a DBMS that supports stored procedures will, as its name implies, store it in the database.
Metadata:
Databases store user data, and they also store information about the database itself. Most DBMSs have a set of system tables, which list tables in the database, column names in each table, primary keys, foreign keys, stored procedures, and so forth. Each DBMS has its own functions for getting information about table layouts and database features. JDBC provides the interface DatabaseMetaData, which a driver writer must implement so that its methods return information about the driver and/or DBMS for which the driver is written. For example, a large number of methods return whether or not the driver supports a particular functionality. This interface gives users and tools a standardized way to get metadata. In general, developers writing tools and drivers are the ones most likely to be concerned with metadata.
28
29
2.
EXISTING SYSTEM:
SYSYTEM ANALYSIS
System Analysis is a detailed study of the various operations performed by a system and their relationships within and outside of the system. Here the key question isWhat all problems exist in the present system? What must be done to solve the problem? Analysis begins when a user or manager begins a study of the program using existing system. During analysis, data collected on the various files, decision points and transactions handled by the present system. The commonly used tools in the system are Data Flow Diagram, interviews, etc. Training, experience and common sense are required for collection of relevant information needed to develop the system. The success of the system depends largely on how clearly the problem is defined, thoroughly investigated and properly carried out through the choice of solution. A good analysis model should provide not only the mechanisms of problem understanding but also the frame work of the solution. Thus it should be studied thoroughly by collecting data about the system. Then the proposed system should be analyzed thoroughly in accordance with the needs. System analysis can be categorized into four parts. System planning and initial investigation Information Gathering Applying analysis tools for structured analysis Feasibility study Cost/ Benefit analysis
30
31
3.
FEASIBILITY ANALYSIS
Whatever we think need not be feasible .It is wise to think about the feasibility of any problem we undertake. Feasibility is the study of impact, which happens in the organization by the development of a system. The impact can be either positive or negative. When the positives nominate the negatives, then the system is considered feasible. Here the feasibility study can be performed in two ways such as technical feasibility and Economical Feasibility.
32
33
4.
INPUT DESIGN
SYSTEM DESIGN
Input design is the process of converting user-oriented input to a computer based format. Input design is a part of overall system design, which requires very careful attention .Often the collection of input data is the most expensive part of the system. The main objectives of the input design are: Produce cost effective method of input Achieve highest possible level of accuracy Ensure that the input is acceptable to and understood by the staff.
Input Data:
The goal of designing input data is to make entry easy, logical and free from errors as possible. The entering data entry operators need to know the allocated space for each field; field sequence and which must match with that in the source document. The format in which the data fields are entered should be given in the input form. Here data entry is online; it makes use of processor that accepts commands and data from the operator through a keyboard. The input required is analyzed by the processor. It is then accepted or rejected. Input stages include the following processes: Data Recording Data Transcription Data Conversion Data Verification Data Control Data Transmission Data Correction
34
One of the aims of the system analyst must be to select data capture method and devices, which reduce the number of stages so as to reduce both the changes of errors and the cost. Input types, can be characterized as: External Internal Operational Computerized Interactive
Input files can exist in document form before being input to the computer. Input design is rather complex since it involves procedures for capturing data as well as inputting it to the computer.
OUTPUT DESIGN
Outputs from computer systems are required primarily to communicate the results of processing to users. They are also used to provide a permanent copy of this result for latter consultation. Computer output is the most important and direct source of information to the users. Designing computer output should proceed in an organized well throughout the manner. The right output must be available for the people who find the system easy o use. The outputs have been defined during the logical design stage. If not, they should defined at the beginning of the output designing terms of types of output connect, format, response etc. Various types of outputs are: External outputs Internal outputs Operational outputs Interactive outputs Turn around outputs
All screens are informative and interactive in such a way that the user can fulfill his requirements through asking queries.
35
36
5.
SYSTEM REQUIREMENTS
This management system can be used in Microsoft Windows 98, Windows 2000, Windows NT, Windows XP, Windows Vista, Windows 7, supported for other platform such as Macintosh and UNIX. The system must be running Windows 98, Windows 98 or Windows NT4.0 operating system and must meet the following hardware requirements. For Windows 95 based computers, a 486/66MHz or higher processor with 8MB For Windows 98 based computers, a 500/88MHz or higher processor with 32 MB of RAM For Windows NT based computers, a 488 / 66 MHz or higher processor with 16 MB of RAM For Windows 200 based computers, a 700/850 MHz or higher processor with 512 MB of Ram And so on.
37
Hardware Requirements:
: : : : :
Pentium III 630MHz or above. Minimum 128 MB Minimum 20GB 15 Color monitor 122 Keys
Software Requirements:
38
39
6.
Java is a programming language originally developed by James Gosling at Sun Microsystems (which is now a subsidiary of Oracle Corporation) 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 bytecode (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". Java is currently one of the most popular programming languages in use, and is widely used from application software to web applications. The original and reference implementation Java compilers, virtual machines, and class libraries were developed by Sun from 1995. As of May 2007, in compliance with the specifications of the Java Community Process, Sun relicensed most of its Java technologies under the GNU General Public License. Others have also developed alternative implementations of these Sun technologies, such as the GNU Compiler for Java, GNU Classpath, and Dalvik. Compared to other programming languages, Java are most similar to C. C++ certainly helps us to learn Java more quickly, but you don't need to know C to learn Java. Unlike C++ Java is not a superset of C. What's most special about Java in relation to other programming languages is that it lets you write special programs called applets that can be downloaded from the Internet and played safely within a web browser. Traditional computer programs have far too much access to your system to be downloaded and executed willy-nilly. Although you generally trust the maintainers of various ftp archives and bulletin boards to do basic virus
40
checking and not to post destructive software, a lot still slips through the cracks. Even more dangerous software would be promulgated if any web page you visited could run programs on your system. You have no way of checking these programs for bugs or for out-and-out malicious behavior before downloading and running them. Java solves this problem by severely restricting what an applet can do. A Java applet cannot write to your hard disk without your permission. It cannot write to arbitrary addresses in memory and thereby introduce a virus into your computer. It should not crash your system.
Java Platform:
One characteristic of Java is portability, which means that computer programs written in the Java language must run similarly on any supported hardware/operating-system platform. This is achieved by compiling the Java language code to an intermediate representation called Java bytecode, instead of directly to platform-specific machine code. Java bytecode instructions are analogous to machine code, but are intended to be interpreted by a virtual machine (VM) written specifically for the host hardware. End-users commonly use a Java Runtime Environment (JRE) installed on their own machine for standalone Java applications, or in a Web browser for Java applets.
41
Standardized libraries provide a generic way to access host-specific features such as graphics, threading, and networking. A major benefit of using bytecode is porting. However, the overhead of interpretation means that interpreted programs almost always run more slowly than programs compiled to native executables would. Just-in-Time compilers were introduced from an early stage that compiles bytecode to machine code during runtime.
Implementations:
Sun Microsystems officially licenses the Java Standard Edition platform for Linux, Mac OS X, and Solaris. Although in the past Sun has licensed Java to Microsoft, the license has expired and has not been renewed. Through a network of third-party vendors and licensees, alternative Java environments are available for these and other platforms. Sun's trademark license for usage of the Java brand insists that all implementations be "compatible". This resulted in a legal dispute with Microsoft after Sun claimed that the Microsoft implementation did not support RMI or JNI and had added platform-specific features of their own. Sun sued in 1997 and in 2001 won a settlement of US$20 million, as well as a court order enforcing the terms of the license from Sun. As a result, Microsoft no longer ships Java with Windows, and in recent versions of Windows, Internet Explorer cannot support Java applets without a third-party plug-in. Sun, and others, has made available free Java run-time systems for those and other versions of Windows. Platform-independent Java is essential to the Java EE strategy, and an even more rigorous validation is required to certify an implementation. This environment enables portable server-side applications, such as Web services, Java Servlets, and Enterprise JavaBeans, as well as with embedded systems based on OSGi, using Embedded Java environments. Through the new GlassFish project, Sun is working to create a fully functional, unified open source implementation of the Java EE technologies. 42
Sun also distributes a superset of the JRE called the Java Development Kit (commonly known as the JDK), which includes development tools such as the Java compiler, Javadoc, Jar, and debugger.
Performance:
Programs written in Java have a reputation for being slower and requiring more memory than those written in C. However, Java programs' execution speed improved significantly with the introduction of Just-in-time compilation in 1997/1998 for Java 1.1, the addition of language features supporting better code analysis (such as inner classes, StringBuffer class, optional assertions, etc.), and optimizations in the Java Virtual Machine itself, such as HotSpot becoming the default for Sun's JVM in 2000. Currently, Java code has approximately half the performance of C code. Some platforms offer direct hardware support for Java; there are microcontrollers that can run java in hardware instead of a software JVM, and ARM based processors can have hardware support for executing Java bytecode through its Jazelle option.
In the latter case the responsibility of managing memory resides with the programmer. If the program does not de-allocate an object, a memory leak occurs. If the program attempts to access or de-allocate memory that has already been de-allocated, the result is undefined and difficult to predict, and the program is likely to become unstable and/or crash. This can be partially remedied by the use of smart pointers, but these add overhead and complexity. Note that garbage collection does not prevent "logical" memory leaks, i.e. those where the memory is still referenced but never used. Garbage collection may happen at any time. Ideally, it will occur when a program is idle. It is guaranteed to be triggered if there is insufficient free memory on the heap to allocate a new object; this can cause a program to stall momentarily. Explicit memory management is not possible in Java. Java does not support C/C++ style pointer arithmetic, where object addresses and unsigned integers (usually long integers) can be used interchangeably. This allows the garbage collector to relocate referenced objects and ensures type safety and security. As in C++ and some other object-oriented languages, variables of Java's primitive data types are not objects. Values of primitive types are either stored directly in fields (for objects) or on the stack (for methods) rather than on the heap, as commonly true for objects (but see Escape analysis). This was a conscious decision by Java's designers for performance reasons. Because of this, Java was not considered to be a pure object-oriented programming language. However, as of Java 5.0, autoboxing enables programmers to proceed as if primitive types were instances of their wrapper class. Java contains multiple types of garbage collectors. By default, HotSpot uses the Concurrent Mark Sweep collector, also known as the CMS Garbage Collector. However, there are also several other garbage collectors that can be used to manage the Heap. For 90% of applications in Java, the CMS Garbage Collector is good enough.
44
Syntax:
The syntax of Java is largely derived from C++. Unlike C++, which combines the syntax for structured, generic, and object-oriented programming, Java was built almost exclusively as an object-oriented language. All code is written inside a class, and everything is an object, with the exception of the primitive data types (integers, floating-point numbers, boolean values, and characters), which are not classes for performance reasons. Unlike C++, Java does not support operator overloading and multiple inheritance for classes in order to simplify the language and to prevent possible errors and anti-pattern design. Java uses similar commenting methods to C++. There are three different styles of comment: a single line style marked with two slashes (//), a multiple line style opened with a slash asterisk (/*) and closed with an asterisk slash (*/), and the Javadoc commenting style opened with a slash and two asterisks (/**) and closed with an asterisk slash (*/). The Javadoc style of commenting allows the user to run the Javadoc executable to compile documentation for the program.
45
It contains: The interface between the native windowing system and the Java application; The core of the GUI event subsystem; Several layout managers; The interface to input devices such as mouse and keyboard; and A java.awt.datatransfer package for use with the Clipboard and Drag and Drop. AWT also makes some higher level functionality available to applications, such as: Access to the system tray on supporting systems; and The ability to launch some desktop applications such as web browsers and email clients from a Java application. Neither AWT nor Swing are inherently thread safe. Therefore, code that updates the GUI or processes events should execute on the Event dispatching thread. Failure to do so may result in a deadlock or race condition. To address this problem, a utility class called SwingWorker allows applications to perform time-consuming tasks following user-interaction events in the event dispatching thread.
Implementation:
As AWT is a bridge to the underlying native user interface, its implementation on a new operating system may involve a lot of work, especially for the set of AWT GUI widgets, which require the development from scratch of native peers for each of the AWT widgets. Since the opening of Java, a project called Caciocavallo has been created. It aims to provide a Java API based on the OpenJDK to ease AWT implementation on new systems.. The project has successfully experimented the implementation of AWT widgets using Java2D. All the needed core JDK modifications have since been pushed on OpenJDK 7.
47
SWING
Swing is the primary Java GUI widget toolkit. It is part of Sun Microsystems' Java Foundation Classes (JFC) an API for providing a graphical user interface (GUI) for Java programs. Swing was developed to provide a more sophisticated set of GUI components than the earlier Abstract Window Toolkit. Swing provides a native look and feel that emulates the look and feel of several platforms, and also supports a pluggable look and feel that allows applications to have a look and feel unrelated to the underlying platform.
48
49
components, which delegated the painting to their OS-native "heavyweight" widget, Swing components are responsible for their own rendering. This transposition and decoupling is not merely visual, and extends to Swing's management and application of its own OS-independent semantics for events fired within its component containment hierarchies. Generally speaking, the Swing Architecture delegates the task of mapping the various flavors of OS GUI semantics onto a simple, but generalized, pattern to the AWT container. Building on that generalized platform, it establishes its own rich and complex GUI semantics in the form of the JComponent model.
Loosely-Coupled and MVC- The Swing library makes heavy use of the
Model/View/Controller software design pattern, which conceptually decouples the data being viewed from the user interface controls through which it is viewed. Because of this, most Swing components have associated models (which are specified in terms of Java interfaces), and the programmer can use various default implementations or provide their own. The framework provides default implementations of model interfaces for all of its concrete components. The typical use of the Swing framework does not require the creation of custom models, as the framework provides a set of default implementations that are transparently, by default, associated with the corresponding JComponent child class in the Swing library. In general, only complex components, such as tables, trees and sometimes lists, may require the custom model implementations around the application-specific data structures. To get a good sense of the potential that the Swing architecture makes possible, consider the hypothetical situation where custom models for tables and lists are wrappers over DAO and/or EJB services. Typically, Swing component model objects are responsible for providing a concise interface defining events fired, and accessible properties for the (conceptual) data model for use by the associated JComponent. Given that the overall MVC pattern is a loosely-coupled collaborative object relationship pattern, the model provides the programmatic means for attaching event listeners to the data model object. Typically, these events are model centric (ex: a "row inserted" event in a table model) and are mapped by the JComponent specialization into a meaningful event for the GUI component. 50
For example, the JTable has a model called TableModel that describes an interface for how a table would access tabular data. A default implementation of this operates on a two-dimensional array. The view component of a Swing JComponent is the object used to graphically "represent" the conceptual GUI control. A distinction of Swing, as a GUI framework, is in its reliance on programmatically-rendered GUI controls (as opposed to the use of the native host OS's GUI controls). Prior to Java 6 Update 10, this distinction was a source of complications when mixing AWT controls, which use native controls, with Swing controls in a GUI (see Mixing AWT and Swing components). Finally, in terms of visual composition and management, Swing favors relative layouts (which specify the positional relationships between components) as opposed to absolute layouts (which specify the exact location and size of components). This bias towards "fluid"' visual ordering is due to its origins in the applet operating environment, that frame the design and development of the original Java GUI toolkit. (Conceptually, this view of the layout management is quite similar to that which informs the rendering of HTML content in browsers, and addresses the same set of concerns that motivated the former.)
Relationship to AWT:
AWT and Swing Class Hierarchy Since early versions of Java, a portion of the Abstract Window Toolkit (AWT) has provided platform-independent APIs for user interface components. In AWT, each component is rendered and controlled by a native peer component specific to the underlying windowing system. By contrast, Swing components are often described as lightweight because they do not
51
require allocation of native resources in the operating system's windowing toolkit. The AWT components are referred to as heavyweight components. Much of the Swing API is generally a complementary extension of the AWT rather than a direct replacement. In fact, every Swing lightweight interface ultimately exists within an AWT heavyweight component because all of the top-level components in Swing (JApplet, JDialog, JFrame, and JWindow) extend an AWT top-level container. Prior to Java 6 Update 10, the use of both lightweight and heavyweight components within the same window was generally discouraged due to Z-order incompatibilities. However, later versions of Java have fixed these issues, and both Swing and AWT components can now be used in one GUI without Z-order issues. The core rendering functionality used by Swing to draw its lightweight components is provided by Java 2D, another part of JFC. The following interfaces and its descriptions to be used by the Java swing. Action This interface performed the action with the ActionListener where the multiple controls are used for same purposes BoundedRangeModel This interface defines the data model of components like: sliders and progressBars. ButtonModel It defines the state model for the buttons like: radio buttons, check boxes etc. CellEditor This interface used by the developer for creating the new editor and it has the new components implement interfaces. The CellEditor implements the wrapper based approach. ComboBoxEditor In this interface, the editor component uses JComboBox components. 52
ComboBoxModel This interface represents the data model in a list model with the selected items. DesktopManager This interface has JDesktopPane object. The JInternalFrame implements in the JDesktopPane, with the help of DesktopManager. Icon This interface used to graphical representation of the components. It has fixed size picture. JComboBox.KeySelectionManager This interface has KeySelectionManager and used for the combo box data model. ListCellRenderer This interface used for paint the cell in the list with the help of "rubber stamps". ListModel This interface used for JList components method. It gets the value of each cell of list. ListSelectionModel This interface indicates the components, which are stable or not. MenuElement This interface used where the any components are implements in the menu. MutableComboBoxModel This interface extends from the ComboBoxModel. It is a mutable version of ComboBoxModel. 53
Renderer It defines the requirements of an object for displaying the values. RootPaneContainer This interface uses the RootPane properties and it has the components like: JFrame, JInternalFrame and JWindow etc. Scrollable This interface provides the scrolling to show the large amount of data with the help of JScrollPane. ScrollPaneConstants This interface used for JScrollPane components. SingleSelectionModel This interface used to select the one index in a model. SwingConstants You can set the components on the screen to own requirements. UIDefaults.ActiveValue It constructs the DefaultListCellRenderer. UIDefaults.LazyValue This enables one to store an entry in the default table. The entered value is not constructed until first time is a real value is created through it using LazyValue.createValue() method. WindowConstants This interface has two methods setDefaultCloseOperation getDefaultCloseOperation and provides the window close opration. and
54
JAVA 2D
In computing, Java 2D is an API for drawing two-dimensional graphics using the Java programming language. Every Java 2D drawing operation can ultimately be treated as filling a shape using a paint and compositing the result onto the screen.
Organization:
The Java 2D API and its documentation are available for download as a part of JDK 6. Java 2D API classes are organised into the following packages in JDK 6: java.awt: The main package for the Java Abstract Window Toolkit. java.awt.geom: The Java standard library of two dimensional geometric shapes such as lines, ellipses, and quadrilaterals. java.awt.font: The library for manipulating glyphs in Java. java.awt.color: The library dealing with the many different ways that color can be represented. java.awt.image: The library for manipulating graphical images. java.awt.print: The library of tools for writing to paper.
Basic Concepts:
These objects are a necessary part of every Java 2D drawing operation. Shapes A shape in Java 2D is a boundary which defines an inside and an outside. Pixels inside the shape are affected by the drawing operation, those outside are not. Trying to fill a straight line segment will result in no pixels being affected, as such a shape does not contain any pixels itself. Instead, a thin rectangle must be used so that the shape contains some pixels.
55
Paints A paint generates the colors to be used for each pixel of the fill operation. The simplest paint is java.awt.Color, which generates the same color for all pixels. More complicated paints may produce gradients, images, or indeed any combination of colors. Filling a circular shape using the color yellow results in a solid yellow circle, while filling the same circular shape using a paint that generates an image produces a circular cutout of the image. Composites During any drawing operation, there is a source (the pixels being produced by the paint) and a destination (the pixels already onscreen). Normally, the source pixels simply overwrite the destination pixels, but the composite allows this behavior to be changed. The composite, given the source and destination pixels, produces the final result that ultimately ends up onscreen. The most common composite is java.awt.AlphaComposite, which can treat the pixels being drawn as partially transparent, so that the destination pixels show through to some degree. Filling To fill a shape, the first step is to identify which pixels fall inside the shape. These pixels will be affected by the fill operation. Pixels that are partially inside and partially outside the shape may be affected to a lesser degree if antialiasing is enabled. The paint is then asked to generate a color for each of the pixels to be painted. In the common case of a solid-color fill, each pixel will be set to the same color. The composite takes the pixels generated by the paint and combines them with the pixels already onscreen to produce the final result.
Advanced Objects:
These objects can be viewed as performing their duties in terms of the simpler objects described above.
56
Transform Every Java 2D operation is subject to a transform, so that shapes may be translated, rotated, sheared, and scaled as they are drawn. The active transform is most often the identity transform, which does nothing. Filling using a transform can be viewed as simply creating a new, transformed shape and then filling that shape. Stroke In addition to the fill operation, Java 2D provides a draw operation. While fill draws the interior of a shape, draw draws its outline. The outline can be as simple as a thin line, or as complicated as a dashed line with each dash having rounded edges. The object responsible for generating the outline is the stroke. Given an input shape, the stroke produces a new shape representing its outline. For instance, an infinitely thin line segment (with no interior) might be stroked into a onepixel-wide rectangle. A draw operation can therefore be described as creating a new, stroked object and then filling that object. Technically speaking, the stroke is only required to accept an input shape and produce a new shape. The stroke implementation provided with Java 2D implements the outline rules described above, but a custom-written stroke could produce any shape it wished. Optimizations Conceptually, drawing a straight black line in Java 2D can be thought of as creating a line segment, transforming it according to the current transform, stroking it to create a thin rectangle, querying this shape to compute the pixels being affected, generating the pixels using java.awt.Color.BLACK, and then compositing the results onto the screen. However, performing this entire sequence of steps for each drawing operation would be very inefficient. Java 2D therefore optimizes common drawing 57
operations so that many of these steps can be skipped. If the paint is a simple solid color, for instance, there is no need to actually command it to generate a list of colors to be painted. Likewise, if the default fully-opaque composite is in use, actually asking it to perform the compositing operation is unnecessary and would waste effort. Java 2D performs the minimum amount of work necessary to make it seem as if it is performing all of these steps for each operation, therefore retaining both great flexibility and high performance.
58
59
7.
Client-server architecture can be considered as a network environment that exchanges information between a server machine and a client machine where server has some resources that can be shared by different clients. In Client-server architecture individual computers known as clients are connected to a central computer this is known as a server. Lets take an example of a file server to understand the core process of a client/server network, the file server acts as a storage space on the network for the files, spreadsheets, databases, etc. Instead of storing these records on every individual computer, the file server allows the clients to store their files on one central computer and make them sharable. The client-server architecture is beneficial in reducing the multiple iterations of a single file and allowing the organization to have one centralized point for every computer to access the same file.
The interaction between a lamp and an electrical socket can be considered as a interaction between client and server is just like. In the example the electrical socket is just like a server and the lamp works like a client. 60
Client-Server Architecture:
Client-server architecture can be considered as a network environment that exchanges information between a server machine and a client machine where server has some resources that can be shared by different clients.
61
NETWORK DATAGRAM
In a network environment the client and the server communicate with eachother by reliable channel like TCP socket which have dedicated point-to-point channel between client and server. All data sent over the channel is received and sent in the same order.
Networking in Java
In this section we are exploring the java.net package which provides the support for networking in java with a generic style. All the java classes for developing a network program are defined in the java.net package.
62
Datagrams are simply bundles of information data passed between machines. Java implements datagrams on top of the UDP protocol by using three classes which are in java.net package as well as define as under: Datagram Socket Datagram Packet Multicast Socket In which the Datagram Packet is used to contain data for sent and receive by a application and the Datagram Socket is used to send or receive the Datagram Packets over the network environment. Whereas the Multicast socket is used to broadcast the Datagram Packets to multiple recipients.
63
The main purpose of the server socket is to listen an incoming connection request and ordinary socket is used to ask to server for the connection. Once a connection between client and server established, both the connected socket can communicate with each other. In other hand we can consider the work of port in connection-based communication is like a medium through which, an application establish a connection with another application by binding a socket by a port number. Addressing the information and the port no., accompanied the data transfer 64
over the network. The Ports are used by TCP and UDP to deliver the data to the right application, are identified by a 16-bit number. It will take effect of registering the application with the system to receive all data bound for that port. There is a limitation for the port that no port can be bound by two applications at the same time.
65
Some of them are given below:Reserved Port Numbers Service echo daytime ftp telnet smtp finger http pop3 Port no. 7 13 21 23 25 79 80 110
If we consider the range of the port numbers, there are 0 to 65,535 ports available. The port numbers ranging from 0 - 1023 are reserved ports or we can say that are restricted ports. All the 0 to 1023 ports are reserved for use by well-known services such as FTP, telnet and http and other system services. These ports are called well-known ports.
66
DIAGRAM REPRESENTATION
SERVER
CLIENT 1
CLIENT 2
DATABASE
67
68
public class ChatClientGUI extends JFrame implements ActionListener { JLabel header; JButton send,clear,connect,disconnect; JTextField ip,port,username; Socket S; threadrecieve tr; JTextArea msg=new JTextArea(),main=new JTextArea(); public ChatClientGUI() {
setTitle("ChatClient"); 69
JPanel panel = new JPanel(); JPanel msgP = new JPanel(new BorderLayout()); JPanel mains = new JPanel(new FlowLayout()); JPanel Head = new JPanel(new BorderLayout()); JPanel sends = new JPanel(new BorderLayout()); JScrollPane mainscroll = new JScrollPane(main); JScrollPane msgscroll = new JScrollPane(msg); panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); panel.setLayout(new BorderLayout()); main.setLineWrap(true); msg.setLineWrap(true); mains.add(new JLabel("Host")); mains.add(ip=new JTextField(10)); mains.add(new JLabel("Port")); mains.add(port=new JTextField(5)); mains.add(new JLabel("Username:")); mains.add(username = new JTextField(5)); port.setText("27000"); port.setEditable(false); mains.add(connect=new JButton("Connect")); mains.add(disconnect=new JButton("Disconnect")); Head.add(mains,BorderLayout.SOUTH); 70
Head.add(header=newJLabel("ChatClient"),BorderLayout.NORTH); panel.add(Head,BorderLayout.NORTH); msgP.add(mainscroll,BorderLayout.CENTER); panel.add(msgP,BorderLayout.CENTER); sends.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); sends.add(msgscroll,BorderLayout.CENTER); sends.add(send=new JButton("Send"),BorderLayout.EAST); panel.add(sends,BorderLayout.SOUTH);
sends.setPreferredSize(new Dimension(100,100));
PrintWriter pw = new PrintWriter(S.getOutputStream()); pw.println("0x007"); pw.flush(); System.exit(0); } catch(Exception E) {} } } ); add(panel); setSize(640, 480); this.setResizable(false); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); setVisible(true); } public void actionPerformed(ActionEvent ae) { String str = ae.getActionCommand(); if(str.equals("Connect") && username.getText().length()>=1) { try 72
{ S = new Socket(ip.getText(),27000); PrintWriter pw = new PrintWriter(S.getOutputStream()); pw.println(username.getText()); pw.flush(); BufferedReader br = new BufferedReader(new InputStreamReader(S.getInputStream())); String ms=br.readLine(); if(ms.equals("ok")) { tr = new threadrecieve(S); tr.start(); connect.setEnabled(false); disconnect.setEnabled(true); username.setEditable(false); ip.setEditable(false); } else { S.close(); JOptionPane.showMessageDialog(null, "Username already in use","Error", JOptionPane.ERROR_MESSAGE); } 73
} catch(Exception E) { JOptionPane.showMessageDialog(null, E.toString(),"Error", JOptionPane.ERROR_MESSAGE); } } if(str.equals("Disconnect")) { try { PrintWriter pw = new PrintWriter(S.getOutputStream()); pw.println("0x007"); pw.flush(); connect.setEnabled(true); disconnect.setEnabled(false); username.setEditable(true); ip.setEditable(true); } catch(Exception E) { } }
74
if(str.equals("Send")) { try { PrintWriter pw = new PrintWriter(S.getOutputStream()); pw.println(msg.getText()); pw.flush(); msg.setText(""); } catch(Exception E) { } } } public class threadrecieve extends Thread { Socket S; String msg; BufferedReader br; threadrecieve(Socket r) { S=r; 75
} public void run() { try { System.out.println("rock"); br = new BufferedReader(new InputStreamReader(S.getInputStream())); while((msg=br.readLine())!=null) { System.out.println(msg); ChatClientGUI.this.main.append(msg+"\n"); if(msg.equals("Server is Shutting Down")) { username.setEditable(true); ip.setEditable(true); disconnect.setEnabled(false); connect.setEnabled(true); break; } } S.close(); br.close(); } 76
77
public class ChatServerGUI extends JFrame implements ActionListener { private static final long serialVersionUID = 7526472295622776147L; JLabel header; JButton send,clear,start,stop; JTextField port; JList userListBox; DefaultListModel userList; threadserver ts; int no_of_users; boolean serverState = false; String com; Vector<Socket> SocketClients = new Vector<Socket>(); 78
JTextArea msg=new JTextArea(),main=new JTextArea(); ServerSocket SS; Socket C; public ChatServerGUI() { setTitle("ChatServer"); JPanel panel = new JPanel(); JPanel msgP = new JPanel(new BorderLayout()); JPanel mains = new JPanel(new FlowLayout()); JPanel Head = new JPanel(new BorderLayout()); JPanel sends = new JPanel(new BorderLayout()); JPanel userPane = new JPanel(new BorderLayout()); userList = new DefaultListModel(); userListBox = new JList(userList); JPanel msgbuttons = new JPanel(new GridLayout(0,2,5,5)); JScrollPane mainscroll = new JScrollPane(main); JScrollPane msgscroll = new JScrollPane(msg);
panel.add(userPane,BorderLayout.EAST); main.setLineWrap(true); msg.setLineWrap(true); mains.add(new JLabel("Port")); mains.add(port=new JTextField(5)); mains.add(start=new JButton("StartService")); mains.add(stop=new JButton("StopService")); stop.setEnabled(false); port.setText("27000"); port.setEditable(false); Head.add(mains,BorderLayout.SOUTH); Head.add(header=new JLabel("Chat Server"),BorderLayout.NORTH); panel.add(Head,BorderLayout.NORTH); msgP.add(mainscroll,BorderLayout.CENTER); panel.add(msgP,BorderLayout.CENTER); sends.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); sends.add(msgscroll,BorderLayout.CENTER); sends.add(msgbuttons,BorderLayout.EAST); msgbuttons.add(send=new JButton("Send"));
80
msgbuttons.add(clear=new JButton("Clear")); panel.add(sends,BorderLayout.SOUTH); sends.setPreferredSize(new Dimension(50,50)); main.setEditable(false); add(panel); setSize(640, 480); this.setResizable(false); start.addActionListener(this); stop.addActionListener(this); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { try{ Socket dummy; PrintWriter pw; for(int i=0;i<SocketClients.size();i++) { dummy=(Socket)SocketClients.get(i); pw = new PrintWriter(dummy.getOutputStream()); 81
pw.println("Server is Shutting Down"); pw.flush(); } System.exit(0); } catch(Exception E) {} } } ); setVisible(true); try{ Thread.sleep(1000); main.append("Welcome to Phoenix, \n"); main.append("please wait...\n"); Thread.sleep(2000); main.append("Click StartService to Start Listening on port 27000\n"); } catch(Exception E) { send.addActionListener(this); }
82
if(str.equals("StartService")) { try {
JOptionPane.showMessageDialog(null, "Running!", "Ready to accept new clients", JOptionPane.INFORMATION_MESSAGE); serverState=true; SS = new ServerSocket(27000); ts = new threadserver(SS); ts.start(); stop.setEnabled(true); start.setEnabled(false); } catch(Exception E) { } } if(str.equals("StopService")) { try
83
{ Socket dummy; PrintWriter pw; serverState=false; main.setText(main.getText()+"\n===SERVER CLOSED===\n"); for(int i=0;i<SocketClients.size();i++) { dummy=(Socket)SocketClients.get(i); pw = new PrintWriter(dummy.getOutputStream()); pw.println("Server is Shutting Down"); pw.flush(); } userList.clear(); SocketClients.clear(); SS.close(); start.setEnabled(true); stop.setEnabled(false); } catch(Exception E) { } } 84
if(str.equals("Send")) { PrintWriter pw; try { Socket dummy; for(int i=0;i<SocketClients.size();i++) { dummy=(Socket)SocketClients.get(i); pw=new PrintWriter(dummy.getOutputStream()); pw.println(">>>>>>>>SERVER:"+msg.getText()); main.append(">>>>>>>>SERVER:"+msg.getText()+"\n"); msg.setText(""); pw.flush(); } } catch(Exception E) { } } }
85
public class threadserver extends Thread { ServerSocket s; Socket C; threadserver(ServerSocket k) { s=k; } public void run() { boolean proceed=true; no_of_users=0; try { ChatServerGUI.this.main.append(">Ready to accept clients\n"); while(true) { C = s.accept(); no_of_users++; BufferedReader br = new BufferedReader(new InputStreamReader(C.getInputStream())); PrintWriter pw = new PrintWriter(C.getOutputStream());
86
String ms = br.readLine(); for(int i=0;i<userList.size();i++) { if(ms.equalsIgnoreCase((String)userList.get(i))) { pw.println("not ok"); pw.flush(); C.close(); proceed=false; break; } proceed=true; } if(proceed) { pw.println("ok"); pw.flush(); SocketClients.add(C); threadclient client; client = new threadclient(C); client.setName(ms); client.start(); 87
} } } catch(Exception E) { } } } public class threadclient extends Thread { Socket c; Socket dummy; String msg; BufferedReader br; PrintWriter pw; boolean clientStatus; threadclient(Socket S) { c=S; } public void run() { 88
try { System.out.println("texting"); br = new BufferedReader(new InputStreamReader(c.getInputStream())); pw = new PrintWriter(c.getOutputStream()); pw.println("Welcome to Phoenix"); pw.println("Your Username:"+this.getName()); pw.flush();
for(int j=0;j<SocketClients.size();j++) { dummy=(Socket)SocketClients.get(j); pw = new PrintWriter(dummy.getOutputStream()); pw.println(this.getName()+" has joined the chat"); pw.flush();
89
if(msg.equals("0x007")) { pw.println("You have been Disconnected from the Chat"); pw.flush(); com = this.getName(); SocketClients.removeElement(c); for(int i=0;i<SocketClients.size();i++) { dummy=(Socket)SocketClients.get(i); pw=new PrintWriter(dummy.getOutputStream());
pw.println(ChatServerGUI.this.com+" has left the chat"); pw.flush(); } break; } else if(msg.equals("**users")) { pw.println("\n****USERS****"); for(int i=0;i<userList.size();i++) 90
{ pw.println((String)userList.get(i)); } pw.println(); pw.flush(); } else { System.out.println(msg); msg = this.getName()+": "+msg; System.out.println(msg); ChatServerGUI.this.main.append(msg+"\n"); for(int i=0;i<ChatServerGUI.this.SocketClients.size();i++) { dummy=(Socket)SocketClients.get(i); pw=new PrintWriter(dummy.getOutputStream()); pw.println(msg); //System.out.println(msg); pw.flush(); } } } 91
ChatServerGUI.this.main.append(">>"+this.getName()+" has left the chat\n"); for(int j=0;j<SocketClients.size();j++) System.out.println(SocketClients.get(j)); userList.removeElement(this.getName()); } catch(Exception E) { E.printStackTrace(); } } } public static void main(String[] args) { new ChatServerGUI(); } }
92
93
94
95
96
97
The user now has been connected to the server and ready to chat.
98
99
100
101
102
103
104
9.
CONCLUSION
Our project is only a humble venture to satisfy the needs in a library. Several user friendly coding have also adopted. This package shall prove to be a powerful package in satisfying all the requirements of the organization. The objective of software planning is to provide a frame work that enables the manager to make reasonable estimates made within a limited time frame at the beginning of the software project and should be updated regularly as the project progresses. Last but not the least it is not the work that played the ways to success but ALMIGHTY.
105
106
10.
REFERENCES
Head First Java 2nd Edition APress, Java and Software Design Concepts Cay S. Horstmann Gary Cornell, Core Java Volume 1- Fundamentals Khalid A. Mughal, Java Certification http://java.sun.com http://www.roseindia.net/jdbc/jdbc-access/CreateTable.shtml http://www.jdbc-tutorial.com/
107