intranet chatting

97
PADMANAVA COLLEGE OF ENGINEERING Abstract The goal of this project was to implement a simple, easy to understand and flexible chat server. This is the middle tier in a 3-tier environment and is also called as application server. We have made an attempt to develop a chat server that can be used to negate the problems faced in 2-tier architectures. A group of two or more computer systems linked together is called as a network. There are many types of computer networks , including: local-area networks (LANs) : The computers are geographically close together (that is, in the same building). wide-area networks (WANs) : The computers are farther apart and are connected by telephone lines or radio waves. campus-area networks (CANs) : The computers are withing a limited geographic area, such as a campus or military base. metropolitan-area networks MANs) : A data network designed for a town or city. home-area networks (HANs) : A network contained within a user's home that connects a person's digital devices. In addition to these types, the following characteristics are also used to categorize different types of networks: topology : The geometric arrangement of a computer system. Common topologies include a bus, star , and ring. See the Network topology diagrams in the Quick Reference section. INTRANET CHATTING

Upload: chittaranjan-panigrahi

Post on 24-Oct-2014

219 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

Abstract

The goal of this project was to implement a simple, easy to understand and flexible chat server. This is the middle tier in a 3-tier environment and is also called as application server. We have made an attempt to develop a chat server that can be used to negate the problems faced in 2-tier architectures.

A group of two or more computer systems linked together is called as a network. There are many types of computer networks, including:

local-area networks (LANs) : The computers are geographically close together (that is, in the same building).

wide-area networks (WANs) : The computers are farther apart and are connected by telephone lines or radio waves.

campus-area networks (CANs): The computers are withing a limited geographic area, such as a campus or military base.

metropolitan-area networks MANs): A data network designed for a town or city.

home-area networks (HANs): A network contained within a user's home that connects a person's digital devices.

In addition to these types, the following characteristics are also used to categorize different types of networks:

topology : The geometric arrangement of a computer system. Common topologies include a bus, star, and ring. See the Network topology diagrams in the Quick Reference section.

protocol : The protocol defines a common set of rules and signals that computers on the network use to communicate. One of the most popular protocols for LANs is called Ethernet. Another popular LAN protocol for PCs is the IBM token-ring network .

architecture : Networks can be broadly classified as using either a peer-to-peer or client/server architecture.

Computers on a network are sometimes called nodes. Computers and devices that allocate resources for a network are called servers.

INTRANET CHATTING

Page 2: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

What is Networking?

Computers running on the Internet communicate to each other using either the Transmission Control Protocol (TCP) or the User Datagram Protocol (UDP), as this diagram illustrates:

When you write Java programs that communicate over the network, you are programming at the application layer. Typically, you don't need to concern yourself with the TCP and UDP layers. Instead, you can use the classes in the java.net package. These classes provide system-independent network communication. However, to decide which Java classes your programs should use, you do need to understand how TCP and UDP differ.

TCP

When two applications want to communicate to each other reliably, they establish a connection and send data back and forth over that connection. This is analogous to making a telephone call. If you want to speak to Aunt Beatrice in Kentucky, a connection is established when you dial her phone number and she answers. You send data back and forth over the connection by speaking to one another over the phone lines. Like the phone company, TCP guarantees that data sent from one end of the connection actually gets to the other end and in the same order it was sent. Otherwise, an error is reported.

TCP provides a point-to-point channel for applications that require reliable communications. The Hypertext Transfer Protocol (HTTP), File Transfer Protocol (FTP), and Telnet are all examples of applications that require a reliable communication channel. The order in which the data is sent and received over the network is critical to the success of these applications. When HTTP is used to read from a URL, the data must be received in the order in which it was sent. Otherwise, you end up with a jumbled HTML file, a corrupt zip file, or some other invalid information.

INTRANET CHATTING

Page 3: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

Definition:  TCP (Transmission Control Protocol) is a connection-based protocol that provides a reliable flow of data between two computers.

UDP

The UDP protocol provides for communication that is not guaranteed between two applications on the network. UDP is not connection-based like TCP. Rather, it sends independent packets of data, called datagrams, from one application to another. Sending datagrams is much like sending a letter through the postal service: The order of delivery is not important and is not guaranteed, and each message is independent of any other.

Definition:  UDP (User Datagram Protocol) is a protocol that sends independent packets of data, called datagrams, from one computer to another with no guarantees about arrival. UDP is not connection-based like TCP.

For many applications, the guarantee of reliability is critical to the success of the transfer of information from one end of the connection to the other. However, other forms of communication don't require such strict standards. In fact, they may be slowed down by the extra overhead or the reliable connection may invalidate the service altogether.

Consider, for example, a clock server that sends the current time to its client when requested to do so. If the client misses a packet, it doesn't really make sense to resend it because the time will be incorrect when the client receives it on the second try. If the client makes two requests and receives packets from the server out of order, it doesn't really matter because the client can figure out that the packets are out of order and make another request. The reliability of TCP is unnecessary in this instance because it causes performance degradation and may hinder the usefulness of the service.

Another example of a service that doesn't need the guarantee of a reliable channel is the ping command. The purpose of the ping command is to test the communication between two programs over the network. In fact, ping needs to know about dropped or out-of-order packets to determine how good or bad the connection is. A reliable channel would invalidate this service altogether.

The UDP protocol provides for communication that is not guaranteed between two applications on the network. UDP is not connection-based like TCP.

INTRANET CHATTING

Page 4: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

Rather, it sends independent packets of data from one application to another. Sending datagrams is much like sending a letter through the mail service:

The order of delivery is not important and is not guaranteed, and each message is independent of any others.

Note:  Many firewalls and routers have been configured not to allow UDP packets. If you're having trouble connecting to a service outside your firewall, or if clients are having trouble connecting to your service, ask your system administrator if UDP is permitted.

Understanding Ports

Generally speaking, a computer has a single physical connection to the network. All data destined for a particular computer arrives through that connection. However, the data may be intended for different applications running on the computer. So how does the computer know to which application to forward the data? Through the use of ports.

Data transmitted over the Internet is accompanied by addressing information that identifies the computer and the port for which it is destined. The computer is identified by its 32-bit IP address, which IP uses to deliver data to the right computer on the network. Ports are identified by a 16-bit number, which TCP and UDP use to deliver the data to the right application.

In connection-based communication such as TCP, a server application binds a socket to a specific port number. This has the effect of registering the server with the system to receive all data destined for that port. A client can then rendezvous with the server at the server's port, as illustrated here:

Definition:  The TCP and UDP protocols use ports to map incoming data to a particular process running on a computer.

In datagram-based communication such as UDP, the datagram packet contains the port number of its destination and UDP routes the packet to the appropriate application, as illustrated in this figure:

INTRANET CHATTING

Page 5: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

Port numbers range from 0 to 65,535 because ports are represented by 16-bit numbers. The port numbers ranging from 0 - 1023 are restricted; they are reserved for use by well-known services such as HTTP and FTP and other system services. These ports are called well-known ports. Your applications should not attempt to bind to them.

Networking Classes in the JDK

Through the classes in java.net, Java programs can use TCP or UDP to communicate over the Internet. The URL, URLConnection, Socket, and ServerSocket classes all use TCP to communicate over the network. The DatagramPacket, DatagramSocket, and MulticastSocket classes are for use with UDP.

What Is a URL?

If you've been surfing the Web, you have undoubtedly heard the term URL and have used URLs to access HTML pages from the Web.

It's often easiest, although not entirely accurate, to think of a URL as the name of a file on the World Wide Web because most URLs refer to a file on some machine on the network. However, remember that URLs also can point to other resources on the network, such as database queries and command output.

Definition:  URL is an acronym for Uniform Resource Locator and is a reference (an address) to a resource on the Internet.

INTRANET CHATTING

Page 6: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

The following is an example of a URL which addresses the Java Web site hosted by Sun Microsystems:

As in the previous diagram, a URL has two main components:

Protocol identifier Resource name

Note that the protocol identifier and the resource name are separated by a colon and two forward slashes. The protocol identifier indicates the name of the protocol to be used to fetch the resource. The example uses the Hypertext Transfer Protocol (HTTP), which is typically used to serve up hypertext documents. HTTP is just one of many different protocols used to access different types of resources on the net. Other protocols include File Transfer Protocol (FTP), Gopher, File, and News.

The resource name is the complete address to the resource. The format of the resource name depends entirely on the protocol used, but for many protocols, including HTTP, the resource name contains one or more of the components listed in the following table:

Host Name The name of the machine on which the resource lives.

Filename The pathname to the file on the machine.

Port Number

The port number to which to connect (typically optional).

Reference A reference to a named anchor within a resource that usually identifies a specific location within a file (typically optional).

For many protocols, the host name and the filename are required, while the port number and reference are optional. For example, the resource name for an HTTP URL must specify a server on the network (Host Name) and the path to the document on that machine (Filename); it also can specify a port number and a reference. In the URL for the Java Web site java.sun.com is the host name and the trailing slash is shorthand for the file named /index.html.

INTRANET CHATTING

Page 7: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

Overview of JavaOBJECT ORIENTED PROGRAMMING AND JAVA

Object-oriented Programming was developed because of limitations found in earlier

approaches of programming. To appreciate what OOP does, we need to understand what

these limitations are and how they arose from traditional programming.

PROCEDURAL LANGUAGES

Pascal, C, Basic, FORTRAN, and similar languages are procedural languages. That is, each

statement in the language tells the computer to do something: Get some input, add these

numbers,, divide by 6, display the output. A program in a procedural language is a list of

instructions.

For very small programs no other organizing principle (often called a paradigm) is needed.

The programmer creates the list of instructions, and the computer carries them out.

Division into Functions

When programs become larger, a single list of instructions becomes unwieldy. Few

programmers can comprehend a program of more than a few hundred statements unless it is

broken down into smaller units. For this reason the function was adopted as a way to make

programs more comprehensible to their human creators. (The term functions is used in C++

and C. In other languages the same concept may be referred to as a subroutine, a

subprogram, or a procedure.) A program is divided into functions, and (ideally, at least) each

function has a clearly defined purpose and a clearly defined interface to the other functions in

the program.

The idea of breaking a program into functions can be further extended by grouping a number

of functions together into a larger entity called a module, but the principle is similar:

grouping a number of components that carry out specific tasks.

Dividing a program into functions and modules is one of the cornerstones of structured

programming, the somewhat loosely defined discipline that has influenced programming

organization for more than a decade.

INTRANET CHATTING

Page 8: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

Problems with Structured Programming

As programs grow ever larger and more complex, even the structured programming approach

begins to show signs of strain. You may have heard about, or been involved in, horror stories

of program development. The project is too complex, the schedule slips, more programmers

are added, complexity increases, costs skyrocket, the schedule slips further, and disaster

ensues. Analyzing the reasons for these failures reveals that there are weaknesses in the

procedural paradigm itself. No matter how well the structured programming approach is

implemented, large programs become excessively complex.

What are the reasons for this failure of procedural languages? One of the most crucial is the

role played by data.

Data Undervalued

In a procedural language, the emphasis is on doing things--read the keyboard, invert the

vector, check for errors, and so on. The subdivision of a program into functions continues

this emphasis. Functions do things just as single program statements do. What they do may

be more complex or abstract, but the emphasis is still on the action.

What happens to the data in this paradigm? Data is, after all, the reason for a program's

existence. The important part of an inventory program isn't a function that displays the data,

or a function that checks for correct input; it's the inventory data itself. Yet data is given

second-class status in the organization of procedural languages.

For example, in an inventory program, the data that makes up the inventory is probably read

from a disk file into memory, where it is treated as a global variable. By global we mean that

the variables that constitute the data are declared outside of any function, so they are

accessible to all functions. These functions perform various operations on the data. They

read it, analyze it, update it, rearrange it, display it, write it back to the disk, and so on.

We should note that most languages, such as Pascal and C, also support local variables,

which are hidden within a single function. But local variables are not useful for important

data that must be accessed by many different functions.

INTRANET CHATTING

Page 9: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

Now suppose a new programmer is hired to write a function to analyze this inventory data in

a certain way. Unfamiliar with the subtleties of the program, the programmer creates a

function that accidentally corrupts the. This is easy to do, because every function has

complete access to the data. It's like leaving your personal papers in the lobby of your

apartment building: Anyone can change or destroy them. In the same way, global data can be

corrupted by functions that have no business changing it.

Another problem is that, since many functions access the same data, the way the data is

stored becomes critical. The arrangement of the data can't be changed without modifying all

the functions that access it. If you add new data items, for example, you'll need to modify all

the functions that access the data so that they can also access these new items. It will be hard

to find all such functions, and even harder to modify all of them correctly. It's similar to what

happens when your local supermarket moves the bread from aisle 4 to aisle 12. Everyone

who patronizes the supermarket must figure out where the bread has gone, and adjust their

shopping habits accordingly.What is needed is a way to restrict access to the data, to hide it

from all but a few critical functions. This will protect the data, simplify maintenance, and

offer other benefits as well.

Relationship to the Real World

Procedural programs are often difficult to design. The problem is that their chief

components--functions and data structures--don't model the real world very well. For

example, suppose you are writing a program to create the elements of a graphics user

interface: menus, windows, and so on. Quick now, what functions will you need? What data

structures? The answers are not obvious, to say the least. It would be better if windows and

menus corresponded more closely to actual program elements.

New Data Types

There are other problems with traditional languages. One is the difficulty of creating new

data types. Computer languages typically have several built-in data types: integers, floating-

point numbers, characters, and so on. What if you want to invent your own data type?

Perhaps you want to work with complex numbers, or two dimensional coordinates, or dates—

quantities the built-in data types don’t handle easily. Being able to create your own types is

called extensibility; you can extend the capabilities of the language. Traditional languages

are not usually extensible. Without unnatural convolutions, you can’t bundle together both X

INTRANET CHATTING

Page 10: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

and Y coordinates into a single variable called Point, and then add and subtract values of this

type. The result is that traditional programs are more complex to write and maintain.

The object oriented approach

The fundamental idea behind object-oriented languages is to combine into a single unit both

data and the functions that operate on that data. Such a unit is called an object.

An object’s functions, called member methods in Java, typically provide the only way to

access its data. If you want to read the item and return the value to you, you call a member

function in the object. It will read the item and return the value to you. You can’t access the

data directly. The data is hidden, so it is safe from accidental modification. Data and its

functions are said to be encapsulated into a single entity. Data encapsulation and data hiding

are key terms in the description of object oriented languages.

If you want to modify the data in an object, you know exactly what functions interact with it:

the member functions in the object. No other functions can access the data. This simplifies

writing, debugging, and maintaining the program.

A Java program typically consists of a number of objects, which communicate with each

other by calling one another’s members functions. We should mention that what are called

member functions in C++ are called methods in Java. Also, data items are referred to as

instance variables. Calling an object’s member function is referred to as sending a message

to the object.

An analogy

You might want to think of objects as departments—such as sales, accounting, personnel, and

so on—in a company. Departments provide an important approach to corporate organization.

In most companies (except very small ones), people don’t work on personnel problems one

day, the payroll the next, and then go out in the field as sales people the week after. Each

department has its own personnel, with clearly assigned duties. It also has its own data:

payroll, sales figures, personnel records, inventory, or whatever, depending on the

department.

INTRANET CHATTING

Page 11: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

The people in each department control and operate on those departments data. Dividing the

company into departments makes its easier to comprehend and control the company’s

activities, and helps them maintain the integrity of the information used by the company. The

payroll department, for instance, is responsible for the payroll data. If you are from the sales

department, and you need to know the total of all the salaries paid in the southern region in

July, you don’t just walk into the payroll department and start rummagging through file

cabinets. You send a memo to the appropriate person in the department, and then you wait

for that person to access the appropriate person in the department, and then you wait for that

person to access the data and send you a reply with the information you want. This ensures

that the data is accessed accurately and that it is not corrupted by inept outsiders. (This view

of corporate organization is show in figure). In the same way, objects provide an approach to

program organization, while helping to maintain the integrity of the programs data.

OOP: An approach to organization

Keep in mind that object-oriented programming is not primarily concerned with the details of

program operation. Instead, it deals with the overall organization of the program.

Characteristics of object-oriented languages:

Let’s briefly examine a few of the major elements of object-oriented languages in general and

Java in particular.

Objects

When you approach a programming problem in an object oriented language, you no longer

ask how the problem will be divided into functions, but how it will be divided into objects.

Thinking in terms of objects, rather than functions, has a surprisingly helpful effect on how

easily programs can be designed and objects in the real world.

What kinds of things become objects-oriented programs? The answer to this is limited only

by your imagination, but there are some typical categories to start you thinking:

INTRANET CHATTING

Page 12: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

Physical objects

Automobile in a traffic-flow simulation

Electrical components in a circuit design to a program

Countries in an economics model

Aircraft in an air-traffic control system

Elements of the computer-user environment

o Windows

o Menus

o Graphics objects(lines ,rectangles, circles)

o The mouse and the keyboard

Programming constructs

o Customized arrays

o Stacks

o Linked lists

Collection of data

o An inventory

o A personnel file

o A dictionary

A table of the latitudes and longitudes of world cities

User defined data types

o Time

o Angles

o Complex numbers

o Points on the plane

Components in a computer games

Ghosts in maze game

Positions in a board game (chess, checkers)

Animals in an ecological simulation

Opponents and friends in adventure games

INTRANET CHATTING

Page 13: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

The match between programming objects and real-world objects us the happy result of

combining data and functions: the resulting objects offer a revolution in program designing,

no such close match between programming constructs and the items being modelled exists in

a procedural language.

Classes

In OOP we say that objects are members of classes. What does this mean ? Let’s look at an

analogy. Almost all computer languages have built-in data types. For instance, a data type

int, meaning integer is pre-defined in Java. You can declare as many variables of type int as

you need in your program:

Int day;

Int count;

Int divisor;

Int answer;

A class serves as a plan, or template. It specifies what data, and what functions will be

included in objects of that class. Defining the class doesn’t create any objects, just as the

mere existence of a type int doesn’t create any variables.

A class is thus a collection of similar objects. This fits our non technical understanding of the

word class, Prince, sting etc., are members of the class of rock musicians. There is no person

called rock musician but specific people with specific names are members of this class if they

possess certain characteristics.

INTRANET CHATTING

Page 14: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

Abstraction

An essential element of object-oriented programming is abstraction. Humans manage

complexity through abstraction. For example, people do not think of a car as a set of tens of

thousands of individual parts. They think of it as a well-defined object with its own unique

behavior. This abstraction allows people to use a car to drive to the grocery store without

being overwhelmed by the complexity of the parts that form the car. They can ignore the

details of how the engine, transmission, and braking systems work. Instead they are free to

utilize the object as a whole.

A powerful way to manage abstraction is through the use of hierarchical classifications. This

allows you to layer the semantics of complex systems, breaking them into more manageable

pieces. From the outside, the car is a single object. Once inside, you see that the car consists

of several subsystems: steering, brakes, sound system, seat belts, heating, cellular phone, and

so on. In turn, each of these subsystems is made up of more specialized units. For instance,

the sound system consists of a radio, a CD player, and/or a tape player. The point is that you

manage the complexity of the car(or any other complex system) through the use of

hierarchical abstractions.

Hierarchical abstractions of complex systems can also be applied to computer programs. The

data from a traditional process-oriented program can be transformed by abstraction into its

component objects. A sequence of process steps can become a collection of messages

between these objects. Thus, each of each object describes its own unique behavior. You

can treat these objects as concrete entities that respond to messages telling them to do

something. This is the essence of object-oriented programming.

Object-oriented concepts form the heart of Java just as they form the basis for human

understanding. It is important that you understand how these concepts translate into

programs. As you will see, object-oriented programming is a powerful and natural paradigm

for creating programs that survive the inevitable changes accompanying the life cycle of any

major software project, including conception, growth, and aging. For example, once you

have a well-defined objects and clean, reliable interfaces to those objects, you can gracefully

decommission or replace parts of an older system without fear.

Encapsulation

INTRANET CHATTING

Page 15: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

Encapsulation is the mechanism that binds together code and the data it manipulates, and

keeps both safe from outside interference and misuse. One way to think about encapsulation

is as a protective wrapper that prevents the code and data from being arbitrarily accessed by

other code defined outside the wrapper. Access to the code and data inside the wrapper is

tightly controlled through a well-defined interface. To relate this to the real world, consider

the automatic transmission on an automobile. It encapsulates hundreds of bits of information

about your engine, such as how much you are accelerating, the pitch of the surface you are

on, and the position of the shift lever. You , as the user, have only one method of affecting

this complex encapsulation: by moving the gear-shift lever. You can’t affect the transmission

by using the turn signal or windshield wipers, for example. Thus, the gear-shift lever is a

well-defined (indeed, unique) interface to the transmission. Further, what occurs inside the

transmission does not affect objects outside the transmission. For example, shifting gears

does not turn on the headlights! Because an automatic transmission is encapsulated , dozens

of car manufacturers can implement one in any way they please. However, from the driver’s

point of view, they all work the same. This same idea can be applied to programming. The

power of encapsulated code is that everyone knows how to access it and thus can use it

regardless of the implementation details—and without fear of unexpected side effects.

In Java the basis of encapsulation is the class. Although the class will be examined in great

detail later in this book, the following brief discussion will be helpful now. A class defines

the structure and behavior(data and code) that will be shared by a set of objects. Each object

of a given class contains the structure and behavior defined by the class, as if it were stamped

out by a mold in the shape of the class. For this reason, objects are sometimes referred to as

instances of a class. Thus, a class is a logical construct; an object has physical reality.

When you create a class, you will specify the code and data that constitute that class.

Collectively, these elements are called members of the class. Specifically, the data defined

by the class are referred to as member variables or instance variables. The code that operates

on that data is referred to as member methods or just methods.

Since the purpose of a class is to encapsulate complexity, there are mechanisms for hiding the

complexity of the implementation inside the class. Each method or variable in a class may be

marked private or public. The public interface of a class represents everything that external

users of the class need to know, or may know. The private methods and data can only be

accessed by code that is a member of the class. Therefore, any other code that is not a

INTRANET CHATTING

Page 16: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

member of the class cannot access a private method or variable. Since the private members

of a class may only be accessed by other parts of your program through the class’ public

methods, you can ensure that no improper actions take place. Of course, this means that the

public interface should be carefully designed not to expose too much of the inner workings of

a class.

Inheritance

Inheritance is the process by which one object acquires the properties of another object. This

is important because it supports the concept of hierarchical classification. As mentioned

earlier, most knowledge is made manageable by hierarchical ( that is, top-down)

classifications. For example, a Golden Retriever is part of the classification dog, which in

turn is part of the mammal class, which is under the larger class animal. Without the use of

hierarchies, each object would need to define all of its characteristics explicitly. However, by

use of inheritance, an object need only define those qualities that make it unique within its

class. It can inherit its general attributes from its parent. Thus, it is the inheritance

mechanism that makes it possible for one object to be a specific instance of a more general

case.

Most people naturally view the world as made up of objects that are related to each other in a

hierarchical way, such as animals, mammals, and dogs. If you wanted to describe animals in

an abstract way, you would say they have some attributes, such as size, intelligence, and type

of skeletal system. Animals also have certain behavioral aspects; they ear, breathe, and sleep.

This description of attributes and behavior is the class definition for animals.

If you wanted to describe a more specific class of animals, such as mammals, they would

have more specific attributes, such as type of teeth, and mammary glands. This is known as a

subclass of animals, where animals are referred to as mammals’ super class.

Since mammals are simply more precisely specified animals, they inherit all of the attributes

from animals. A deeply inherited subclass inherits all of the attributes from each of its

ancestors in the class hierarchy.

Inheritance interacts with encapsulation as well. If a given class encapsulates some

attributes, then any subclass will have the same attributes plus any that it adds as part of its

INTRANET CHATTING

Page 17: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

specialization (see Figure 2-2). This is a key concept which lets object-oriented programs

grow in complexity linearly rather than geometrically. A new subclass inherits all of the

attributes of all of its ancestors. It does not have unpredictable interactions with the majority

of the rest of the code in the system.

Polymorphism

Polymorphism (from the Greek, meaning “many forms”) is a feature that allows one interface

to be used for a general class of actions. The specific action is determined by the exact nature

of the situation. Consider a stack ( which is a last-in, first-out list ). You might have a

program that requires three types of stack. One stack is used for integer values, one for

floating-point values, and one for characters. The algorithm that implements each stack is the

same, even though the data being stored differs. In a non-object-oriented language, you

would be required to create three difference sets of stack routines, with each set using

different names. However, because of polymorphism, in Java you can specify a general set

of stack routines that all share the same names.

More generally, the concept of polymorphism is often expressed by the phrase “one interface,

multiple methods.” This means that it is possible to design a generic interface to a group of

related activities. This helps reduce complexity by allowing the same interface to be used to

specify a general class of action. It is the compiler’s job to select the specific action ( that is,

method ) as it applies to each situation. You, the programmer, do not need to make this

selection manually. You need only remember and utilize the general interface.

Extending the dog analogy, a dog’s sense of smell is polymorphic. If the dog smells a cat, it

will bark and run after it. If the dog smells its food, it will salivate and run to its bowl. The

same sense of smell is at work in both situations. The difference is what is being smelled,

that is, the type of data being operated upon by the dog’s nose! This same general concept

can be implemented in Java as it applies to methods within a Java program.

Polymorphism, Encapsulation, and Inheritance Work Together

When properly applied, polymorphism, encapsulation, and inheritance combine to produce a

programming environment that supports the development of far more robust and scaleable

INTRANET CHATTING

Page 18: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

programs than does the process-oriented model. A well-designed hierarchy of classes is the

basis for reusing the code in which you have invested time and effort developing and testing.

Encapsulation allows you to migrate your implementations over time without breaking the

code that depends on the public interface of your classes. Polymorphism allows you to create

clean, sensible, readable, and resilient code.

Of the two real-world examples, the automobile more completely illustrates the power of

object-oriented design. Dogs are fun to think about from an inheritance standpoint, but cars

are more like programs. All drivers rely on inheritance to drive different types

( subclasses ) of vehicles. Whether the vehicle is a school is a school bus, a Mercedes sedan,

a Porsche, or the family minivan, drivers can all more or less find and operate the steering

wheel, the brakes, and the accelerator. After a bit of gear grinding, most people can even

manage the difference between a stick shift and an automatic, because they fundamentally

understand their common super class, the transmission.

People interface with encapsulated features on cars all the time. The brake and gas pedals

hide an incredible array of complexity with an interface so simple you can operate them with

your feet! The implementation of the engine, the style of brakes, and the size of the tires

have no effect on how you interface with the class definition of the pedals.

The final attribute, polymorphism, is clearly reflected in the ability of car manufacturers to

offer a wide array of options on basically the same vehicle. For example, you can get an

antilock braking system or traditional brakes, power or rack-and-pinion steering, 4-, or 6-, or

8-cylender engines. Either way, you will still press the break pedal to stop, turn the steering

wheel to change direction, and press the accelerator when you want to move.

INTRANET CHATTING

Page 19: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

An Overview of RMI Applications

RMI applications are often comprised of two separate programs: a server and a client. A typical server application creates some remote objects, makes references to them accessible, and waits for clients to invoke methods on these remote objects. A typical client application gets a remote reference to one or more remote objects in the server and then invokes methods on them. RMI provides the mechanism by which the server and the client communicate and pass information back and forth. Such an application is sometimes referred to as a distributed object application.

Distributed object applications need to

Locate remote objects: Applications can use one of two mechanisms to obtain references to remote objects. An application can register its remote objects with RMI's simple naming facility, the rmiregistry, or the application can pass and return remote object references as part of its normal operation.

Communicate with remote objects: Details of communication between remote objects are handled by RMI; to the programmer, remote communication looks like a standard Java method invocation.

Load class bytecodes for objects that are passed around: Because RMI allows a caller to pass objects to remote objects, RMI provides the necessary mechanisms for loading an object's code, as well as for transmitting its data.

The following illustration depicts an RMI distributed application that uses the registry to obtain a reference to a remote object. The server calls the registry to associate (or bind) a name with a remote object. The client looks up the remote object by its name in the server's registry and then invokes a method on it. The illustration also shows that the RMI system uses an existing Web server to load class bytecodes, from server to client and from client to server, for objects when needed.

INTRANET CHATTING

Page 20: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

Advantages of Dynamic Code Loading

One of the central and unique features of RMI is its ability to download the bytecodes (or simply code) of an object's class if the class is not defined in the receiver's virtual machine. The types and the behavior of an object, previously available only in a single virtual machine, can be transmitted to another, possibly remote, virtual machine. RMI passes objects by their true type, so the behavior of those objects is not changed when they are sent to another virtual machine. This allows new types to be introduced into a remote virtual machine, thus extending the behavior of an application dynamically. The compute engine example in this chapter uses RMI's capability to introduce new behavior to a distributed program.

Remote Interfaces, Objects, and Methods

Like any other application, a distributed application built using Java RMI is made up of interfaces and classes. The interfaces define methods, and the classes implement the methods defined in the interfaces and, perhaps, define additional methods as well. In a distributed application some of the implementations are assumed to reside in different virtual machines. Objects that have methods that can be called across virtual machines are remote objects.

An object becomes remote by implementing a remote interface, which has the following characteristics.

A remote interface extends the interface java.rmi.Remote. Each method of the interface declares java.rmi.RemoteException in its

throws clause, in addition to any application-specific exceptions.

RMI treats a remote object differently from a nonremote object when the object is passed from one virtual machine to another. Rather than making a copy of the implementation object in the receiving virtual machine, RMI passes a remote stub for a remote object. The stub acts as the local representative, or proxy, for the remote object and basically is, to the caller,

INTRANET CHATTING

Page 21: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

the remote reference. The caller invokes a method on the local stub, which is responsible for carrying out the method call on the remote object.

A stub for a remote object implements the same set of remote interfaces that the remote object implements. This allows a stub to be cast to any of the interfaces that the remote object implements. However, this also means that only those methods defined in a remote interface are available to be called in the receiving virtual machine.

Creating Distributed Applications Using RMI

When you use RMI to develop a distributed application, you follow these general steps.

1. Design and implement the components of your distributed application. 2. Compile sources and generate stubs.

3. Make classes network accessible.

4. Start the application.

Design and Implement the Application Components

First, decide on your application architecture and determine which components are local objects and which ones should be remotely accessible. This step includes:

Defining the remote interfaces: A remote interface specifies the methods that can be invoked remotely by a client. Clients program to remote interfaces, not to the implementation classes of those interfaces. Part of the design of such interfaces is the determination of any local objects that will be used as parameters and return values for these methods; if any of these interfaces or classes do not yet exist, you need to define them as well.

Implementing the remote objects: Remote objects must implement one or more remote interfaces. The remote object class may include implementations of other interfaces (either local or remote) and other methods (which are available only locally). If any local classes are to be used as parameters or return values to any of these methods, they must be implemented as well.

Implementing the clients: Clients that use remote objects can be implemented at any time after the remote interfaces are defined, including after the remote objects have been deployed.

INTRANET CHATTING

Page 22: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

Compile Sources and Generate Stubs

This is a two-step process. In the first step you use the javac compiler to compile the source files, which contain the implementation of the remote interfaces and implementations, the server classes, and the client classes. In the second step you use the rmic compiler to create stubs for the remote objects. RMI uses a remote object's stub class as a proxy in clients so that clients can communicate with a particular remote object.

Make Classes Network Accessible

In this step you make everything--the class files associated with the remote interfaces, stubs, and other classes that need to be downloaded to clients--accessible via a Web server.

Start the Application

Starting the application includes running the RMI remote object registry, the server, and the client.

The rest of this lesson walks through the steps to create a compute engine.

Building a Generic Compute Engine

This trail focuses on a simple yet powerful distributed application called a compute engine. The compute engine, a remote object in the server, takes tasks from clients, runs them, and returns any results. The tasks are run on the machine where the server is running. This sort of distributed application could allow a number of client machines to make use of a particularly powerful machine or one that has specialized hardware.

The novel aspect of the compute engine is that the tasks it runs do not need to be defined when the compute engine is written. New kinds of tasks can be created at any time and then given to the compute engine to be run. All that is required of a task is that its class implement a particular interface. Such a task can be submitted to the compute engine and run, even if the class that defines that task was written long after the compute engine was written and started. The code needed to accomplish the task can be downloaded by the RMI system to the compute engine, and then the engine runs the task, using the resources on the machine on which the compute engine is running.

The ability to perform arbitrary tasks is enabled by the dynamic nature of the Java platform, which is extended to the network by RMI. RMI dynamically loads the task code into the compute engine's Java virtual machine and runs

INTRANET CHATTING

Page 23: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

the task without prior knowledge of the class that implements the task. An application like this, which has the ability to download code dynamically, is often called a behavior-based application. Such applications usually require full agent-enabled infrastructures. With RMI such applications are part of the basic mechanisms for distributed computing on the Java platform.

System Analysis

System development can be general ly thought of as having two major components, System Analysis and System Design. System Analysis is a process of gathering and interpreting the facts, diagnosing problem and using information to recommend improvements to the system. This is the job of the System Analyst.

System Design

The process of planning a new business system or to replace or complement

an existing system and to determine how the proposed the system can be used

to make its operation more effective. It consists of the following activities :

Preliminary Investigation Determination of System Requirements

System Design

Development of software

System Testing

Implementation and Evaluation

2.1 Feasibil ity Study

The importance of feasibility study is to determine that the system requested

by the client is feasible or not. The aspects in the feasibility study are :

Technical Feasibility Economic Feasibility

Operational Feasibility

INTRANET CHATTING

Page 24: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

User Requirement Analysis

The requirements of the user are essential for building a computer based

information system. The following points have to be taken into consideration.

System Analysis

Requirement Analysis is the first phase in the software development process.

The main objective of the phase is to identify the problem and the system to

be developed. The later phases are strictly dependent on this phase and hence

the system analyst needs to be clear and precise about this phase. Any

inconsistency in this phase will lead to a lot of problems in the other phases

that follow. Hence there will be several reviews before the final copy of the

analysis is made on the system to be developed. After all the analysis is

completed the System Analyst will submit the details of the system to be

developed in the form of a document called Requirement Specification.

Requirements – Determination

It is the process by which the analyst gains knowledge of the organization

and applies in selecting right technology for a particular application.

Conducting interviews in the existing system users and corporate executives.

Various manuals and reports of the existing system are studied; various

inputs to the system and various outputs of the system are identified by

studying the existing reports. The specification of the input process and the

outputs are discussed in the Software Requirement Specification.

Problem – Definition

The first step in an initial investigation, is to define the problem that led to

the problem which must be stated, clearly understood and agreed upon by the

user and try to achieve the result, emphasis being on logical requirements of

INTRANET CHATTING

Page 25: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

the problem rather than the physical requirements. Requirements may be

confirmed eliciting information through one of the following strategies :

Asking the customer what they want exactly

Prototyping start improving the entity system, a step at a time, achieving

of real

Life changes from which further adjustments can be made

FEASIBILITY STUDY

Technical Feasibility

It determines whether the organization has the technology and skills

necessary to carry out the project and how this is obtained. The system is

technically feasible on the following grounds :

All necessary technology exists to develop the system

The existing resource are capable and can hold all the necessary data

The system is too flexible and can be expanded further

The system can give guarantees of accuracy, ease of use, reliability and

data security

The system can give instant response to inquiries.

So, we can conclude that “N-Tier Architecture” is technically feasible.

Operational Feasibility

This determines if the proposed system has satisfied user objectives and can

be fitted into the current system operation. The present system is

operationally feasible, on the following grounds :

INTRANET CHATTING

Page 26: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

The methods of processing and presentation are completely accepted to the

clients since they can meet all the user requirements

The clients have been involved in the planning and development of the

system

The proposed system will not cause any problem under any circumstances

The proposed system will certainly satisfy the user requirements and will also

enhance their capability. It can be best fitted into current operations. Also

there is no need to replace any existing staff. Therefore, the system is

operationally feasible.

Economical Feasibility

It determines whether the project goal can be within the resource limits

allocated to it . It must determine whether it is worth while to process with the

project all or whether the benefit obtained from the new system is not worth

the costs. After conducting cost benefit analysis, it reveals that the objectives

of the proposed system can be achieved within the allocated resources.

Proposed system require no extra man power, cost almost nil. Also the cash

invested to implement the proposed system can be easily recovered. So the

system is economically feasible.

GENERAL DESCRIPTION

System’s Description

This project consists of 3 modules. Server Module, Middleware and Client

Module. The Client Module developed using SWING API’s of Java, the

Administration Server using TCP/IP Network programming, the Application

server using JDBC-ODBC Bridge and as the backend the Oracle 8 i server is

used.

Scope of Work

INTRANET CHATTING

Page 27: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

The scope of this project work includes the following activities :

Study of Java API’s – SWING for the development of friendly user

interface.

Study of Java Network (TCP/IP) programming classes in order to facilitate

communication between Clients – Middleware – Application Server

Study of Java JDBC classes in order to facilitate communication between

Application Server – Database Server

Functional Aspects

The following steps give the sequence of functionality of the project :

This project consists of 3 modules. Server Module, Middleware and Client

Module. In order to increase the efficiency and capabilities of processing the

quires and to have On-line administration of clients, the Middle layer is

further divided into Administration server and Application server.

The Client connects to the Administration Server in order to send queries

to be processed by the Application server. The Administration server

verifies the rights (Read, Write, Execute) of the client and accordingly

forwards the query to the Application server.

The Application server then connects to an Oracle Server, processes the

request and returns the information to the client through the

Administration server.

PERFORMANCE REQUIREMENTS

The performance of the module is upto the requirements of the user.

Administrative Aspects

INTRANET CHATTING

Page 28: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

The Database and Network administration of Gorgeous Ltd., has been

simplified by providing a Middleware between Clients and the Database

Server.

Through the Middleware the DBA can know the list of online clients that

were connected to the database server.

Apart from viewing them online, he can also monitor and control the

access to their centralized database.

Through this aspect the Database and Network Administration of Gorgeous

Ltd., has become very easy.

System Design

It is a solution of how to approach the creation of a system. This important

phase provides the understanding and procedural details necessary for

implementing the system recommended in the feasibility study. The design

step produces a Data Design, Architectural Design and Procedural Design.

The Data Design transforms the information domain model created during

analysis into data structures that may be required to implement the software.

The Architectural Design defines the relationship among the user structural

components into a procedural description of the software. The source code

generated and testing is conducted to integrate and validate the software.

From a project management point of view, software design is conducted in

two steps. Preliminary Design is concerned with the transformation of the

Requirements into data and software architecture. The Detailed Design

focuses on refinements to the architectural representation that leads to the

detailed data structure and algorithmic representations of software.

Logical Design

The logical design of an information system is analogous to an engineering

blueprint or conceptual view of an automobile. It shows the major features

and how they are related to one another. The detailed specifications are

INTRANET CHATTING

Page 29: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

drawn on the basis of user requirements. The outputs, inputs and the

relationship between the variables are designed in this phase.

The objectives of a database are accuracy, integrity and successful

recovery from failure, privacy and security of data and good overall

performance.

Input Design

It is the bridge between users and information system. It specifies the

manger in which data enters the system for processing. It can ensure the

reliability of the system and produce reports from accurate data or it may

result in the output of erroneous information. On line data entry is available

which accepts input from the keyboard and data is displayed on the screen for

verification. While designing, the following points have been taken into

consideration:

Input formats are designed as per the user requirements

Interaction with the user is maintained in simple dialogues

Appropriate fields are locked thereby allowing only valid inputs

Output Design

Each and every activity in this work is result oriented. The most important

feature of an information system for users is the output. Efficient

intelligent output design improves the usability and acceptability of the

system and also helps in decision making. Hence the following points are

considered during the output design :

What information is to be presented

INTRANET CHATTING

Page 30: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

Whether to display or print the information

How to arrange the information in an acceptable format

How the status has to be maintained each and every time

How to distribute the output to the recipients

The system being user friendly in nature is served to fulfill the

requirements of the user. Suitable screen designs are made and produced to

the user for refinements. The main requirement of the user is the retrieval of

all the relevant information related to a particular user.

Data Design

It is the first of the three design activities that are conducted during software engineering. The impact of data structure on the program structure and procedural complexity causes data design to have a profound influence and software quality. The concepts of information hiding and data abstraction provide the foundation for an approach to data design.

SOFTWARE REQUIREMENTS:

SYSTEM:

WINDOWS NT 4 | 2000 | 9.X | ME | ANY

JDK 1.4 onwards

Textpad

HRS (Hardware Requirement Specification)

INTRANET CHATTING

Page 31: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

PIV 500MHZ or above

64MB RAM

20MB Free Hard disk space

Std. Color Monitor

Network interface card or Modem

CODINGPROGRAM OF APPLET SERVER

//import classes

import java.awt.event.*;

import java.net.*;

import java.io.*;

import java.util.*;

import javax.swing.Timer;

//Code for the AppServer class

public class AppServer implements Runnable

{

ServerSocket server;

Socket fromClient;

Thread serverThread;

INTRANET CHATTING

Page 32: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

public AppServer()

{

System.out.print("FunChat server started..........");

try

{

server = new ServerSocket(1001);

serverThread = new Thread(this);

serverThread.start();

}

catch(Exception e)

{

System.out.println("Cannot start the thread: " + e);

}

}

public static void main(String args[])

{

new AppServer();

}

public void run()

{

try

{

INTRANET CHATTING

Page 33: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

while(true)

{

//Listening to the clients request

fromClient = server.accept();

//Creating the connect object

Connect con = new Connect(fromClient);

}

}

catch(Exception e)

{

System.out.println("Cannot listen to the client" + e);

}

}

}

//Code for the connect class

class Connect

{

ObjectOutputStream streamToClient;

int ctr=0;

BufferedReader streamFromClient;

static Vector vector;

static Vector vctrList;

String message=" ";

static String str=new String("UsrList");

INTRANET CHATTING

Page 34: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

static

{

vector=new Vector(1,1);

vctrList=new Vector(1,1);

vctrList.addElement((String)str);

}

int verify(String mesg)

{

try

{

RandomAccessFile RAS=new RandomAccessFile("UsrPwd.txt", "r");

int i=0;

String str="";

while((RAS.getFilePointer())!=(RAS.length()))

{

str=RAS.readLine();

if(str.equals(mesg))

{

ctr=1;

break;

}

INTRANET CHATTING

Page 35: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

}

RAS.close();

}

catch(Exception e)

{

}

return ctr;

}//end of verify()

int checkFile(String mesg)

{

int chk=1;

try

{

RandomAccessFile RS=new RandomAccessFile("UsrPwd.txt", "r");

int i=0;

String str="";

String colon=new String(":");

int index=((String)mesg).lastIndexOf(colon);

String userName=(String)mesg.substring(0,index);

INTRANET CHATTING

Page 36: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

while((RS.getFilePointer())!=(int)(RS.length()))

{

str=RS.readLine();

int index1=((String)str).lastIndexOf(colon);

String usrName=(String)str.substring(0,index1);

if(usrName.equals(userName))

{

chk=0;

break;

}

}//end of while

RS.close();

}//end of try

catch(Exception e)

{

}

return chk;

}//end of chkFile

public Connect(Socket inFromClient)

{

INTRANET CHATTING

Page 37: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

//Retrieving the clients stream

String msg="";

String mesg="";

try

{

streamFromClient = new BufferedReader(new InputStreamReader(inFromClient.getInputStream()));

streamToClient= new ObjectOutputStream(inFromClient.getOutputStream());

msg=streamFromClient.readLine();

//mesg=streamFromClient.readLine();

if((msg.equals("From Timer")))

{

streamToClient.writeObject(vector);

streamToClient.writeObject(vctrList);

}

else if(msg.equals("LoginInfo"))

{

msg=streamFromClient.readLine();

int ver=verify(msg);

if(ver==1)

{

String colon=new String(":");

int index=((String)msg).lastIndexOf(colon);

INTRANET CHATTING

Page 38: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

String userName=(String)msg.substring(0,index);

if(!(vctrList.indexOf((String)userName)>0))

{

streamToClient.writeObject("Welcome");

vctrList.addElement((String)userName);

}

}

else

{

streamToClient.writeObject("Login denied");

}

}

else if(msg.equals("RegisterInfo"))

{

msg=streamFromClient.readLine();

int ret=checkFile(msg);

if(ret==0)

streamToClient.writeObject("User Exists");

if(ret==1)

{

FileOutputStream out = new FileOutputStream("UsrPwd.txt",true);

PrintStream p = new PrintStream( out );

INTRANET CHATTING

Page 39: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

p.println();

p.println(msg);

p.close();

streamToClient.writeObject("Registered");

}

}

else if(msg.equals("User Logout"))

{

String remUser=streamFromClient.readLine();

boolean b=vctrList.removeElement((String)remUser);

}

else

{

message=message+msg;

vector.addElement((String)message);

streamToClient.writeObject(vector);

}

}//end of try

catch(Exception e)

{

System.out.println("Cannot get the client stream connect" + e);

INTRANET CHATTING

Page 40: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

}

finally

{

try

{

inFromClient.close();

}

catch(IOException e)

{}

}

}//end of connect

}

INTRANET CHATTING

Page 41: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

PROGRAM OF APPLET CLIENT

import java.io.*;

import java.net.*;

import javax.swing.*;

import java.awt.event.*;

import java.awt.*;

import java.util.*;

import javax.swing.Timer;

public class clientInt extends JFrame implements ActionListener

{

Timer t = new Timer(5000,new TimerAction());

String usr_name;

public String remUser;

class TimerAction implements ActionListener

{

Socket toServer;

ObjectInputStream streamFromServer;

PrintStream streamToServer;

public void actionPerformed(ActionEvent e2)

{

try

INTRANET CHATTING

Page 42: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

{

toServer=new Socket("server",1001);

streamFromServer=new ObjectInputStream(toServer.getInputStream());

streamToServer=new PrintStream(toServer.getOutputStream());

message=txtMsg.getText();

//send a message to the server

streamToServer.println("From Timer");

//receive vectors from the server

Vector vector=(Vector)streamFromServer.readObject();

Vector vector1=(Vector)streamFromServer.readObject();

//show the online users

txtListUsers.setText("");

for(int j=1;j<vector1.capacity();j++)

{

txtListUsers.append((String)vector1.elementAt(j));

txtListUsers.append("\n");

}

//show the messsages

int i=messageCount;

for(;i<vector.capacity();i++)

{

txtMessages.append((String)vector.elementAt(i));

INTRANET CHATTING

Page 43: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

txtMessages.append("\n");

}

messageCount=i;

}//end of try

catch(Exception e)

{

System.out.println("Exception "+e);

}

}//end of actionPerformed

}//end of TimerListener class

int messageCount=0;

String name;

PrintStream streamToServer;

ObjectInputStream streamFromServer;

Socket toServer;

JTextArea txtMessages;

JTextArea txtListUsers;

JTextField txtMsg;

JButton msgSendBtn;

JButton userLoginBtn;

INTRANET CHATTING

Page 44: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

JButton userRegisterBtn;

JButton userLogoutBtn;

JLabel lblChatRoom;

JLabel lblUserList;

JScrollPane jspSendMsgPane;

JScrollPane jspTxtMsgPane;

JScrollPane jspUserListPane;

JTextField textWriteMsg;

String message;

int nSend;

public clientInt(String nm)

{

remUser=nm;

usr_name=nm;

this.setTitle("FunChat: "+usr_name); //set the title name

JPanel panel=new JPanel();

panel.setLayout(new GridBagLayout());

GridBagConstraints gbCons=new GridBagConstraints();

gbCons.gridx=0;

gbCons.gridy=0;

INTRANET CHATTING

Page 45: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

lblChatRoom=new JLabel("Chat Room",SwingConstants.LEFT);

panel.add(lblChatRoom, gbCons);

gbCons.gridx=1;

gbCons.gridy=0;

lblUserList=new JLabel("Online Users",SwingConstants.LEFT);

panel.add(lblUserList, gbCons);

gbCons.gridx=0;

gbCons.gridy=1;

gbCons.gridwidth=1;

gbCons.gridheight=1;

gbCons.weightx=1.0;

gbCons.weighty=1.0;

txtMessages=new JTextArea(25,35);

txtMessages.setEditable(false);

jspTxtMsgPane=new JScrollPane(txtMessages,

JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);

panel.add(jspTxtMsgPane, gbCons);

gbCons.gridx=1;

gbCons.gridy=1;

gbCons.gridwidth=1;

gbCons.gridheight=1;

gbCons.weightx=1.0;

INTRANET CHATTING

Page 46: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

gbCons.weighty=1.0;

txtListUsers=new JTextArea(25,10);

txtListUsers.setEditable(false);

jspUserListPane=new JScrollPane(txtListUsers,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);

panel.add(jspUserListPane, gbCons);

gbCons.gridx=0;

gbCons.gridy=2;

gbCons.gridwidth=1;

gbCons.gridheight=1;

gbCons.weightx=1.0;

gbCons.weighty=1.0;

txtMsg=new JTextField(35);

jspSendMsgPane=new JScrollPane(txtMsg, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);

panel.add(jspSendMsgPane, gbCons);

gbCons.gridx=1;

gbCons.gridy=2;

gbCons.gridwidth=1;

gbCons.gridheight=1;

gbCons.weightx=1.0;

gbCons.weighty=1.0;

gbCons.anchor=GridBagConstraints.WEST;

msgSendBtn=new JButton("Send");

INTRANET CHATTING

Page 47: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

panel.add(msgSendBtn, gbCons);

msgSendBtn.addActionListener(this);

JPanel btnPanel=new JPanel();

userLogoutBtn=new JButton("Logout");

userLogoutBtn.addActionListener(this);

//add a listerener to the window

this.addWindowListener(

new WindowAdapter()

{

public void windowClosing(WindowEvent e1)

{

try

{

Socket toServer;

ObjectInputStream streamFromServer;

PrintStream streamToServer;

toServer=new Socket("server",1001);

streamToServer=new PrintStream(toServer.getOutputStream());

streamToServer.println("User Logout");

streamToServer.println(remUser);

}//end of try

catch(Exception e2)

INTRANET CHATTING

Page 48: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

{

System.out.println("Exception Occured: "+e2);

}

}

}

);

btnPanel.add(userLogoutBtn);

gbCons.gridx=0;

gbCons.gridy=3;

gbCons.gridwidth=1;

gbCons.gridheight=1;

gbCons.weightx=1.0;

gbCons.weighty=1.0;

gbCons.anchor=GridBagConstraints.EAST;

gbCons.fill=GridBagConstraints.HORIZONTAL;

panel.add(btnPanel, gbCons);

getContentPane().add(panel);

setDefaultCloseOperation(EXIT_ON_CLOSE);

setVisible(true);

setSize(546,567);

INTRANET CHATTING

Page 49: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

t.start();

}//end of clientInt()

public void actionPerformed(ActionEvent e1)

{

JButton button=(JButton)e1.getSource();

//if logout button clicked

if(button.equals(userLogoutBtn))

{

try

{

toServer=new Socket("server",1001);

streamToServer=new PrintStream(toServer.getOutputStream());

//send a msg to server for logging out

streamToServer.println("User Logout");

streamToServer.println(remUser);

}

catch(Exception e)

{

System.out.println("Exception Occured: "+e);

}

this.dispose();

}

//else if Send button is clicked

INTRANET CHATTING

Page 50: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

else

{

int num1=0,num2=0,res=0;

String name="";

try

{

toServer=new Socket("server",1001);

streamFromServer=new ObjectInputStream(toServer.getInputStream());

streamToServer=new PrintStream(toServer.getOutputStream());

message=txtMsg.getText();

String msg=message;

//send the user name and msg typed to the server

streamToServer.println(usr_name+":"+msg);

txtMsg.setText("");

//read the reply from the server

Vector vector=(Vector)streamFromServer.readObject();

int i=messageCount;

for(;i<vector.capacity();i++)

{

txtMessages.append((String)vector.elementAt(i)); //display the messages

txtMessages.append("\n");

}//end of for

INTRANET CHATTING

Page 51: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

messageCount=i;

}//end of try

catch(Exception e)

{

System.out.println("Exception "+e);

}

}//end of else

}//actionPerformed()

public static void main(String args[])

{

String nm=new String();

clientInt CI=new clientInt(nm);

}

}//end of class

INTRANET CHATTING

Page 52: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

PROGRAM FOR LOGIN USER

//import classes

import java.io.*;

import java.net.*;

import javax.swing.*;

import java.awt.event.*;

import java.awt.*;

import java.util.*;

import javax.swing.Timer;

public class Login extends JFrame implements ActionListener

{

//declare components

JLabel lblUserName;

JLabel lblUserPwd;

JTextField txtUsrName;

JPasswordField txtUsrPwd;

JButton btnLogin;

JButton btnCancel;

JButton btnRegister;

String UsrName;

char[] UsrPwd;

String strPwd;

INTRANET CHATTING

Page 53: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

Socket toServer;

ObjectInputStream streamFromServer;

PrintStream streamToServer;

public Login()

{

this.setTitle("Login"); //set the title

JPanel panel=new JPanel();

panel.setLayout(new GridBagLayout());

GridBagConstraints gbCons=new GridBagConstraints();

//place the components on the frame

gbCons.gridx=0;

gbCons.gridy=0;

lblUserName=new JLabel("Enter Username ");

panel.add(lblUserName, gbCons);

gbCons.gridx=1;

gbCons.gridy=0;

txtUsrName=new JTextField(20);

panel.add(txtUsrName, gbCons);

gbCons.gridx=0;

gbCons.gridy=1;

lblUserPwd=new JLabel("Enter Password ");

INTRANET CHATTING

Page 54: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

panel.add(lblUserPwd, gbCons);

gbCons.gridx=1;

gbCons.gridy=1;

txtUsrPwd=new JPasswordField(20);

panel.add(txtUsrPwd, gbCons);

JPanel btnPanel=new JPanel();

btnLogin=new JButton("Login");

btnPanel.add(btnLogin);

btnLogin.addActionListener(this); //add listener to the Login button

btnRegister=new JButton("Register");

btnPanel.add(btnRegister);

btnRegister.addActionListener(this); //add listener to the Register button

btnCancel=new JButton("Cancel");

btnPanel.add(btnCancel);

btnCancel.addActionListener(this); //add listener to the Cancel button

gbCons.gridx=1;

gbCons.gridy=3;

gbCons.anchor=GridBagConstraints.EAST;

panel.add(btnPanel, gbCons);

getContentPane().add(panel);

setVisible(true);

setSize(450,200);

INTRANET CHATTING

Page 55: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

setDefaultCloseOperation(EXIT_ON_CLOSE);

}

//show the error message

void showdlg()

{

JOptionPane.showMessageDialog(this,"Invalid Password or Login name", "Message", JOptionPane.ERROR_MESSAGE);

}

public void actionPerformed(ActionEvent e1)

{

JButton button=(JButton)e1.getSource();

if(button.equals(btnCancel))

{

this.dispose(); //close the current frame

}

else if(button.equals(btnRegister))

{

new Register(); //call Register program

this.dispose();

}

else

{

INTRANET CHATTING

Page 56: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

try

{

//create socket and input-output socket streams

toServer=new Socket("server",1001);

streamFromServer=new ObjectInputStream(toServer.getInputStream());

streamToServer=new PrintStream(toServer.getOutputStream());

//send message to server for login

streamToServer.println("LoginInfo");

UsrName=txtUsrName.getText();

UsrPwd=txtUsrPwd.getPassword();

strPwd=new String(UsrPwd);

//send the user name and password to the server

streamToServer.println(UsrName+":"+strPwd);

//read the message from the server

String frmServer=(String)streamFromServer.readObject();

if(frmServer.equals("Welcome"))

{

new clientInt(UsrName); //start the chat screen

this.dispose();

}

else

{

INTRANET CHATTING

Page 57: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

showdlg();//show error message

}

}//end of try

catch(Exception e)

{

System.out.println("Exception Occured: "+e);

}

}//end of if..else

}//end of actionPerformed

public static void main(String args[])

{

new Login();

}

}//end of class Login

INTRANET CHATTING

Page 58: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

PROGRAM TO REGISTER USER

//import classes

import java.io.*;

import java.net.*;

import javax.swing.*;

import java.awt.event.*;

import java.awt.*;

import java.util.*;

public class Register extends JFrame implements ActionListener

{

//declare components

JLabel lblHeading;

JLabel lblUserName;

JLabel lblUserPwd;

JLabel lblCnfUserPwd;

JLabel lblFrstName;

JLabel lblLstName;

JLabel lblAge;

JLabel lblEmpId;

JLabel lblSex;

String usrName;

char[] usrPwd;

INTRANET CHATTING

Page 59: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

char[] cnfPwd;

String frstName;

String lstName;

String age;

String empid;

Socket toServer;

ObjectInputStream streamFromServer;

PrintStream streamToServer;

JComboBox lstSex;

JTextField txtUserName;

JPasswordField txtUsrPwd;

JPasswordField txtCnfUsrPwd;

JTextField txtFrstName;

JTextField txtLstName;

JTextField txtAge;

JTextField txtEmpId;

Font f;

Color r;

JButton btnSubmit;

JButton btnCancel;

public Register()

{

this.setTitle("Register");

INTRANET CHATTING

Page 60: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

JPanel panel=new JPanel();

//apply the layout

panel.setLayout(new GridBagLayout());

GridBagConstraints gbCons=new GridBagConstraints();

//place the components

gbCons.gridx=0;

gbCons.gridy=0;

lblHeading=new JLabel("Registration Info");

Font f = new Font("Monospaced" , Font.BOLD , 24);

lblHeading.setFont(f);

Color c=new Color(0,200,0);

lblHeading.setForeground(new Color(131,25,38));

lblHeading.setVerticalAlignment(SwingConstants.TOP);

gbCons.anchor=GridBagConstraints.EAST;

panel.add(lblHeading, gbCons);

gbCons.gridx = 0;

gbCons.gridy = 1;

lblUserName = new JLabel("Enter Username");

gbCons.anchor=GridBagConstraints.WEST;

panel.add(lblUserName, gbCons);

gbCons.gridx=1;

gbCons.gridy=1;

txtUserName=new JTextField(15);

INTRANET CHATTING

Page 61: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

panel.add(txtUserName, gbCons);

gbCons.gridx=0;

gbCons.gridy=2;

lblUserPwd=new JLabel("Enter Password ");

panel.add(lblUserPwd, gbCons);

gbCons.gridx = 1;

gbCons.gridy = 2;

txtUsrPwd = new JPasswordField(15);

panel.add(txtUsrPwd, gbCons);

gbCons.gridx=0;

gbCons.gridy=3;

lblCnfUserPwd=new JLabel("Confirm Password ");

panel.add(lblCnfUserPwd, gbCons);

gbCons.gridx=1;

gbCons.gridy=3;

txtCnfUsrPwd=new JPasswordField(15);

panel.add(txtCnfUsrPwd, gbCons);

gbCons.gridx=0;

gbCons.gridy=4;

lblEmpId=new JLabel("Employee ID");

panel.add(lblEmpId, gbCons);

INTRANET CHATTING

Page 62: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

gbCons.gridx=1;

gbCons.gridy=4;

txtEmpId=new JTextField(15);

panel.add(txtEmpId, gbCons);

gbCons.gridx=0;

gbCons.gridy=5;

lblFrstName=new JLabel("First Name");

panel.add(lblFrstName, gbCons);

gbCons.gridx=1;

gbCons.gridy=5;

txtFrstName=new JTextField(15);

panel.add(txtFrstName, gbCons);

gbCons.gridx=0;

gbCons.gridy=6;

lblLstName=new JLabel("Last Name");

panel.add(lblLstName, gbCons);

gbCons.gridx = 1;

gbCons.gridy = 6;

txtLstName=new JTextField(15);

panel.add(txtLstName, gbCons);

gbCons.gridx=0;

INTRANET CHATTING

Page 63: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

gbCons.gridy=7;

lblAge=new JLabel("Age");

panel.add(lblAge, gbCons);

gbCons.gridx=1;

gbCons.gridy=7;

txtAge=new JTextField(3);

panel.add(txtAge, gbCons);

gbCons.gridx=0;

gbCons.gridy=8;

lblSex=new JLabel("Sex");

panel.add(lblSex, gbCons);

gbCons.gridx = 1;

gbCons.gridy=8;

String[] sex= {"Male", "Female"};

JComboBox lstSex=new JComboBox(sex);

lstSex.setSelectedIndex(0);

panel.add(lstSex, gbCons);

JPanel btnPanel=new JPanel();

btnSubmit=new JButton("Submit");

btnPanel.add(btnSubmit);

btnSubmit.addActionListener(this); //add listener to the Submit button

btnCancel=new JButton("Cancel");

INTRANET CHATTING

Page 64: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

btnPanel.add(btnCancel);

btnCancel.addActionListener(this); //add listener to the Cancel button

gbCons.gridx=0;

gbCons.gridy=9;

gbCons.anchor=GridBagConstraints.EAST;

panel.add(btnPanel, gbCons);

getContentPane().add(panel);

setDefaultCloseOperation(EXIT_ON_CLOSE);

setVisible(true);

setSize(450,400);

}//end or Register()

public void actionPerformed(ActionEvent e1)

{

JButton button=(JButton)e1.getSource(); //get the source of the event

if(button.equals(btnCancel))

{

this.dispose();

}

else

INTRANET CHATTING

Page 65: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

{

int ver=verify(); //call the verify()

if(ver==1)

{

try

{

//establish a socket connection and create I/O socket streams

toServer=new Socket("server",1001);

streamFromServer=new ObjectInputStream(toServer.getInputStream());

streamToServer=new PrintStream(toServer.getOutputStream());

//send a message to server for Registration

streamToServer.println("RegisterInfo");

usrName=txtUserName.getText();

usrPwd=txtUsrPwd.getPassword();

String pwd=new String(usrPwd);

//send the user name and password to the server

streamToServer.println(usrName+":"+pwd);

//read the response from the server

String frmServer=(String)streamFromServer.readObject();

if(frmServer.equals("Registered"))

{

INTRANET CHATTING

Page 66: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

new Login();

this.dispose();

}

else if(frmServer.equals("User Exists"))

{

showUsrExists(); //show error message

}

}//end of try

catch(Exception e)

{

System.out.println("Exception "+e);

}

}//end of if

}//end of else

}//end of actionPerformed()

int verify() //test the validity of the user information

{

int ctr=0;

int intAge=0;

try

{

usrName=txtUserName.getText();

INTRANET CHATTING

Page 67: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

usrPwd=txtUsrPwd.getPassword();

cnfPwd=txtCnfUsrPwd.getPassword();

frstName=txtFrstName.getText();

lstName=txtLstName.getText();

age=txtAge.getText();

empid=txtEmpId.getText();

String strUsrPwd=new String(usrPwd);

String strCnfPwd=new String(cnfPwd);

try

{

intAge =(int)Integer.parseInt(age.trim());

}

catch(Exception e)

{

showErrordlgInt();

}

if((usrName.length()>0)&&(strUsrPwd.length()>0)&&(strCnfPwd.length()>0)&&(frstName.length()>0)&&(lstName.length()>0)&&(intAge>21)&&(intAge<58)&&(empid.length()>0)&&(strUsrPwd.equals(strCnfPwd)))

{

System.out.println("done");

ctr=1;

return ctr;

}

else

{

showErrordlg();

INTRANET CHATTING

Page 68: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

}//end of else

}//end of try

catch(Exception e)

{

System.out.println("exception thrown "+e);

}//end of catch

return ctr;

}//end of verify()

//error msg- User Exists

void showUsrExists()

{

JOptionPane.showMessageDialog(this,"User exists.", "Message", JOptionPane.ERROR_MESSAGE);

}

int flg=0;

//error msg- Incorrect Entry

void showErrordlg()

{

JOptionPane.showMessageDialog(this,"Incorrect entry.", "Message", JOptionPane.ERROR_MESSAGE);

}

//error msg- Incorrect Age entered

INTRANET CHATTING

Page 69: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

void showErrordlgInt()

{

JOptionPane.showMessageDialog(this,"Age incorrect.", "Message", JOptionPane.ERROR_MESSAGE);

}

public static void main(String args[])

{

new Register();

}

}//end of class

Output ScreensINTRANET CHATTING

Page 70: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

INTRANET CHATTING

Page 71: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

INTRANET CHATTING

Page 72: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

INTRANET CHATTING

Page 73: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

INTRANET CHATTING

Page 74: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

INTRANET CHATTING

Page 75: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

INTRANET CHATTING

Page 76: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

INTRANET CHATTING

Page 77: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

INTRANET CHATTING

Page 78: Intranet Chatting

PADMANAVA COLLEGE OF ENGINEERING

BIBLIOGRAPHY

1. Java Network Program - OREILLY

By Elliotte Rusty Harold

2. Data Base Program with JDBC and Java-OREILLY

By George Reese

3. Java Complete Reference -Tata McGraw Hill

By Patrick Naughton Herbert Schildt

4. Swing By Manning

INTRANET CHATTING