Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
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.
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
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
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. Defi nition: 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. 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.
INTRANET CHATTING
Not e: 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:
Defi nition: 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
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.
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. Defi nition: URL is an acronym for Uniform Resource Locator and is a reference (an address) to a resource on the Internet.
The following is an example of a URL which addresses the Java Web site hosted by Sun Microsystems:
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
INTRANET CHATTING
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).
Referenc A reference to a named anchor within a resource that usually e 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.
Overview of Java
OBJECT 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
INTRANET CHATTING
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.
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.
INTRANET CHATTING
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 secondclass 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.
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
INTRANET CHATTING
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 datesquantities the built-in data types dont 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 cant bundle together both X 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 objects 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 cant 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.
INTRANET CHATTING
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 anothers 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 objects member function is referred to as sending a message to the object.
An analogy You might want to think of objects as departmentssuch as sales, accounting, personnel, and so onin a company. Departments provide an important approach to corporate organization. In most companies (except very small ones), people dont work on personnel problems one day, the payroll the next, and then go out in the field as sales people the week after. sales figures, personnel records, inventory, or whatever, depending on the department. Each department has its own personnel, with clearly assigned duties. It also has its own data: payroll,
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 companys 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 dont 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.
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: Lets 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:
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
INTRANET CHATTING
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
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 ? Lets 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;
INTRANET CHATTING
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 doesnt create any objects, just as the mere existence of a type int doesnt 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.
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.
INTRANET CHATTING
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 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 cant 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 drivers 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 detailsand without fear of unexpected side effects.
INTRANET CHATTING
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 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.
INTRANET CHATTING
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 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
INTRANET CHATTING
related activities. This helps reduce complexity by allowing the same interface to be used to specify a general class of action. It is the compilers 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 dogs 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 dogs 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 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.
INTRANET CHATTING
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.
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
INTRANET CHATTING
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
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, 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.
INTRANET CHATTING
interfaces are defined, including after the remote objects have been deployed.
INTRANET CHATTING
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 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 generally 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
2.1 Feasibility 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
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 the
INTRANET CHATTING
problem rather than the physical requirements. Requirements may be confirmed eliciting information through one of the following strategies:
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: The methods of processing and presentation are completely accepted to the clients since they can meet all the user requirements
INTRANET CHATTING
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 Systems Description This project consists of 3 modules. Server Module, Middleware and Client Module. The Client Module developed using SWING APIs of Java, the Administration Server using TCP/IP Network programming, the Application server using JDBC-ODBC Bridge and as the backend the Oracle 8i server is used. Scope of Work The scope of this project work includes the following activities:
INTRANET CHATTING
Study of Java APIs 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 The Database and Network administration of Gorgeous Ltd., has been simplified by providing a Middleware between Clients and the Database Server.
INTRANET CHATTING
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 drawn on the basis of user requirements. The outputs, inputs and the relationship between the variables are designed in this phase.
INTRANET CHATTING
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 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
INTRANET CHATTING
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.
INTRANET CHATTING
CONTEXT DIAGRAM
USER
Registration Confirmation Chat room User info Receive Message info
INTRANET CHATTING
INTRANET CHATTING
LEVEL 1 DFD
Request User Registration
USER
Validate Login
m roo ation at Ch nform i er Us e ssa me o n nd ati Se form in
ge essa ive m Rece rmation info
Password
User Id
status
Send/Receive Message
INTRANET CHATTING
USER
m m
Us Infor er matio n
SOFTWARE REQUIREMENTS:
PIV 500MHZ or above 64MB RAM 20MB Free Hard disk space Std. Color Monitor Network interface card or Modem
CODING
PROGRAM OF APPLET SERVER
INTRANET CHATTING
//import classes import java.awt.event.*; import java.net.*; import java.io.*; import java.util.*; import javax.swing.Timer;
public AppServer() { System.out.print("FunChat server started.........."); try { server = new ServerSocket(1001); serverThread = new Thread(this); serverThread.start(); } catch(Exception e)
INTRANET CHATTING
public void run() { try { 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);
INTRANET CHATTING
} }
//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");
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;
} } RAS.close(); } catch(Exception e) {
return ctr;
INTRANET CHATTING
}//end of verify()
int checkFile(String mesg) { int chk=1; try { RandomAccessFile RS=new RandomAccessFile("UsrPwd.txt", "r"); int i=0;
String userName=(String)mesg.substring(0,index); 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;
INTRANET CHATTING
return chk;
}//end of chkFile
public Connect(Socket inFromClient) { //Retrieving the clients stream String msg=""; String mesg=""; try { streamFromClient = new InputStreamReader(inFromClient.getInputStream())); BufferedReader(new
msg=streamFromClient.readLine();
INTRANET CHATTING
//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); String userName=(String)msg.substring(0,index); if(! (vctrList.indexOf((String)userName)>0)) { streamToClient.writeObject("Welcome"); vctrList.addElement((String)userName); } } else {
INTRANET CHATTING
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 ); 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); }
INTRANET CHATTING
else
}//end of try catch(Exception e) { System.out.println("Cannot get the client stream connect" + e); }
INTRANET CHATTING
}//end of connect }
INTRANET CHATTING
import java.io.*; import java.net.*; import javax.swing.*; import java.awt.event.*; import java.awt.*; import java.util.*; import javax.swing.Timer;
class TimerAction implements ActionListener { Socket toServer; ObjectInputStream streamFromServer; PrintStream streamToServer; public void actionPerformed(ActionEvent e2) {
try
INTRANET CHATTING
txtMessages.append((String)vector.elementAt(i));
INTRANET CHATTING
txtMessages.append("\n");
int messageCount=0; String name; PrintStream streamToServer; ObjectInputStream streamFromServer; Socket toServer;
JTextArea txtMessages; JTextArea txtListUsers; JTextField txtMsg; JButton msgSendBtn; JButton userLoginBtn;
INTRANET CHATTING
public clientInt(String nm) { remUser=nm; usr_name=nm; this.setTitle("FunChat: "+usr_name); //set the title name JPanel panel=new JPanel();
gbCons.gridx=0; gbCons.gridy=0;
INTRANET CHATTING
gbCons.gridx=1; gbCons.gridy=0;
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_SCROLL BAR_AS_NEEDED); panel.add(jspTxtMsgPane, gbCons);
INTRANET CHATTING
panel.add(msgSendBtn, gbCons);
msgSendBtn.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
} );
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
t.start();
//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
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());
//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
messageCount=i;
public static void main(String args[]) { String nm=new String(); clientInt CI=new clientInt(nm); } }//end of class
INTRANET CHATTING
import java.io.*; import java.net.*; import javax.swing.*; import java.awt.event.*; import java.awt.*; import java.util.*; import javax.swing.Timer;
//declare components
JLabel lblUserName; JLabel lblUserPwd; JTextField txtUsrName; JPasswordField txtUsrPwd; JButton btnLogin; JButton btnCancel; JButton btnRegister; String UsrName; char[] UsrPwd; String strPwd;
INTRANET CHATTING
//place the components on the frame gbCons.gridx=0; gbCons.gridy=0; lblUserName=new JLabel("Enter Username "); panel.add(lblUserName, gbCons);
panel.add(lblUserPwd, 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
INTRANET CHATTING
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
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);
if(frmServer.equals("Welcome")) { new clientInt(UsrName); //start the chat screen this.dispose(); } else { showdlg();//show error message
INTRANET CHATTING
}//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
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;
JComboBox lstSex;
JTextField txtUserName; JPasswordField txtUsrPwd; JPasswordField txtCnfUsrPwd; JTextField txtFrstName; JTextField txtLstName; JTextField txtAge; JTextField txtEmpId; Font f; Color r; JButton btnSubmit; JButton btnCancel;
//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);
panel.add(lblCnfUserPwd, gbCons);
INTRANET CHATTING
gbCons.gridx=0; gbCons.gridy=7;
INTRANET CHATTING
gbCons.gridx = 1; gbCons.gridy=8; String[] sex= {"Male", "Female"}; JComboBox lstSex=new JComboBox(sex); lstSex.setSelectedIndex(0); panel.add(lstSex, gbCons);
btnSubmit=new JButton("Submit"); btnPanel.add(btnSubmit); btnSubmit.addActionListener(this); //add listener to the Submit button btnCancel=new JButton("Cancel"); btnPanel.add(btnCancel);
INTRANET CHATTING
getContentPane().add(panel);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true); setSize(450,400);
}//end or Register()
JButton button=(JButton)e1.getSource(); //get the source of the event if(button.equals(btnCancel)) { this.dispose(); } else {
INTRANET CHATTING
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);
//read the response from the server String frmServer=(String)streamFromServer.readObject(); if(frmServer.equals("Registered")) { new Login();
INTRANET CHATTING
int verify() //test the validity of the user information { int ctr=0; int intAge=0; try {
usrName=txtUserName.getText(); usrPwd=txtUsrPwd.getPassword();
INTRANET CHATTING
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.le ngth()>0)&&(lstName.length()>0)&&(intAge>21)&&(intAge<58)&&(empid.length()>0)&&(s trUsrPwd.equals(strCnfPwd))) { System.out.println("done"); ctr=1; return ctr; } 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); }
Output Screens
INTRANET CHATTING
INTRANET CHATTING
INTRANET CHATTING
INTRANET CHATTING
INTRANET CHATTING
INTRANET CHATTING
INTRANET CHATTING
BIBLIOGRAPHY
2. Data Base Program with JDBC and Java -OREILLY By 3. Java Complete Reference By George Reese -Tata McGraw Hill Patrick Naughton Herbert Schildt
4. Swing
By
Manning
INTRANET CHATTING