JAVA Chat Room Program __java

Source: Internet
Author: User
Tags event listener exit in sendmsg thread class server port
Finally finished the experiment, wrote the report and email to the teacher.
has been very lazy, but this program is pretty smooth, with JAVA network programming and multithreading is very convenient, but the interface programming more trouble, but for the sake of my interface do very concise.
But the code is still very ugly beep, too compact, the individual or more like their own coding of C + + program code structure.
This is probably the only thing that I have done carefully and closely related to the course this semester.

Engineering files and programs have been uploaded, but are still in review ... Can be downloaded later in http://download.csdn.net/user/Rappy/.

The report reads as follows:
Multi-threaded multiplayer chat program

Experimental purposes

Write a client/server multithreaded Chat room program with multiple people chatting.

Understand TCP protocols and multithreaded programming.

Learn the basics of chat software.

Experimental content

Chat Room program function Brief:

Chat room program is divided into server side, and client.

Server program as a staging point. All clients communicate only with the server.

The client program logs on with the user name.

Both the server and the client display a list of users online.

Users can post messages to all users.

Experimental Process

(1) using Eclipse as the development tool, JAVA is the development language.

(2) using JAVA sockets and ServerSocket These two classes can be connected to the network without concern for the underlying operations, and the use of DataInputStream and DataOutputStream two classes can be as convenient as the local input output.

Extended JAVA tread class, you can do multithreaded programming without concern for blocking operations, only need to overload its Run method void run ();

(3) The format of the message is composed of a format prefix and content:

Client message:

"L user" means login (log in) server with user name;

"M XXX" means sending a chat message to the server with the content "XXX";

"Q" indicates an exit login (quit).

Service-Side message:

"A user1 user2" means to accept (accept) the user's logon request and send it a list of online users;

"R" indicates a deny (refuse) user's logon request if the user name is already occupied.

"M XXX" indicates that the service side broadcasts a chat message to the online user that the content is "XXX".

"L user" indicates that a user named username is successful and sends a message to the online user that the user is logged on.

"Q user" means that a user named users exits and sends a message to the online user that they are exiting the login.

"Q" indicates that the user's exit logon request is accepted.

(4) Service end

The interface is as follows:

Where server IP is the IP address of this computer, not editable, and server port is the service ports, click the Start button can listen to the port, and the Start button will become a Stop button, click again will disconnect all users, and reset to the Start button. The following figure is in the service state:

A

The service side is made up of a Server class defined as

public class Server extends Frame implements actionlistener{//...}

Represents an inherited JAVA framework class frame and implements the Actionlisstenner interface, which is a window and can listen for user behavior, such as clicking a button.

The main variables are:

Private Boolean serving = false;

Private ServerSocket server;

Private Hashtable HT; Record String UserName-> dataoutputstream out

Private Hashtable ht_s; Record String userName-> Socket Connection

Serving is a global Boolean variable that indicates whether it is in the service. Set to True after clicking the Start button and set to False after clicking the Stop button.

Server is a service socket that listens on ports and accepts user connection requests.

The HT is a hash table that records the user's name to the output stream connected to the user, and is used to broadcast messages to the user.

ht_s is a hash table that records the user's name to the socket connected to the user, and disconnects these connections when the service is stopped.

Some controls are also included in the interface of the program.

B

There are two nested classes within the Server class, all of which are extended thread classes:

Private class Serverthreadsingle extends thread{//...}

Private class Serverthread extends thread{//...}

The second is the thread that listens to the user's logon request, with the main code as follows:

while (serving) {

Socket connection = Server.accept ();

Serverthreadsingle handler = new Serverthreadsingle (connection);

}

That is, when the service, accept the user's connection request, and start a separate service thread (the first thread class) and the user to communicate.

And the primary work of the first thread class is

Initialize a Boolean variable in the constructor of the thread class login = false;

The following tasks are then performed in the Run () method of the thread class:

while (!login) {

Read the message sent by the user.

If the message has a format prefix of ' L ', then determine if the message contains a username

or whether the user name already exists in a hash table HT for recording the user name.

If it is, reply to the message "R" to indicate rejection.

If not, reply to a message "a user1 user2 ..." to accept.

Among them user1, User2, ... Is the list of all current online users, read from the hash table.

Send the message "L Current_User" to these online users,

Current_User is the user name provided by the currently logged-on user.

Adds the user name to the hash table.

A message that the user logon success is exported in the service-side message output area.

Login = true;

}

while (login) {

Receive a message from a user

If the message's format prefix is ' Q ', then the reply message "Q" Prompts the exit to succeed,

Deletes the username from the hash table and broadcasts the message "Q Current_User".

Otherwise, the message is added to the current user name and broadcast to all users (including the current user).

Outputs a message in the service-side message output area.

}

Close connection

C

Event-handling method for the event that the program interface responds to button clicks.

public void actionperformed (ActionEvent event) {//...}

After clicking the Start button, set serving to true and create a new service socket and start service thread, which needs to be read from the interface to the set value of the service port. The Start button then changes to the Stop button.

When you click the Stop button, set serving to false and disconnect all connections, and then the Stop button becomes the Start button.

(5) Client

The interface is as follows:

The user name needs to be populated with its own username (initialized to user) and Server IP needs to be filled in

IP address of the server (initialized to native IP), server port needs to be populated with a listening port

(The default is 8888, no change required). Then click the login button to send a login request to the server.

After logging in, enter the chat message in the message text input area and click the Send button to send the message.

Click the Logout button to exit the login. The following figure, for chat status (run on another machine):

A

The client is made up of one client class, which is defined as:

public class Client extends Frame implements actionlistener{//...}

Represents an inherited JAVA framework class frame and implements the Actionlisstenner interface, which is a window and can listen for user behavior, such as clicking a button.

The main variables are:

Private Boolean login = false; Boolean variable that logs whether to log on

private Socket Connection; Sockets for connection to and service-side

Private Recthread receiver; The thread used to start the receive service-side message

Some controls are also included in the interface of the program.

B

In the time processing method of the Client class, the time from the button login,send,logout is handled separately, mainly by invoking Login (), sendmsg (), quit (), respectively, the three methods.

The login () method is mainly to obtain the login information from the interface and send the login message to the server.

"L UserName". If the message returned by the server is "R", the user is prompted with "User name error", if "a user1 user2 ..." The user name after ' A ' is added to the list of interface controls, and then a thread receiver that receives the server message is started, which is later explained by the thread.

The Sendmsg () method gets the message from the message text input area of the interface, plus the "M" prefix and sends the message to the server.

The Quit () method is primarily to send a message "Q" to the server.

C

The thread receiver used to receive server-side messages is a nested class that extends thread class thread, which is defined as follows:

Private class Recthread extends thread{//...}

The main work in its run () method is:

Read the message from the service side.

If the prefix is ' l ', then the userName after ' l ' is added to the interface control list. and prompts the user to sign in in the message text output area.

If the prefix is ' q ', then judge if the ' Q ' follows UserName, and if so, remove the userName from the interface control list, otherwise the client exits successfully and clears all the user names in the list. and prompts the user to exit in the message text output area.

If the prefix is ' M ', then the message is exported to the message text output area.

(6) Other

The main work in the server class and the constructor of the Client class is to add the event listener for the button and invoke the Setup () method to add the control to the interface in a certain layout using the layout manager.

The interface contains a list of control lists for the listing class that displays the list of online users.

Experimental Summary

The main reference to the "JAVA Language Program Design" (Tsinghua Press, Zhu Fu), to understand the interface programming, multithreaded programming and network programming, the basic points.

Refer to the online documentation for the Hashtable, List class usage.

From this time

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.