Chat system with Java to implement Server-Client structure

zhaozj2021-02-16  62

Say it in front. . .

Recently studied Java, and implemented Socket network programming with Java, I have a little experience in creating a chat system, but I still have a Java beginner, in the face of many masters, I will be shocked, after all, after all Something is shallow, if there is any lack of insufficient or lack of mature, you will have a lot of points after you have seen it. After all, I read Java only watched a week, many advanced methods have not been exposed, it is impossible to completely design a perfect The system, everyone still shared his own experience, after all, heavy in communication.

For the university, the standard Java package provides a fairly complete class library for network communications and I / O related operations, using these classes, can design a network interactive system in a short time. Socket Program allows programmers to have a powerful network system with almost any network communication protocol. To create a Server-Client structure chat system, it is not difficult. This system can be implemented using Socket, I / O operation, and multi-threaded programming.

Analyze the task. . .

Chat systems are not more than two aspects, server-side and clients. Simply analyze the tasks to be completed in terms of two aspects, which is equal to half of the design. Let's take a look at the task of the server:

1. The server should establish a serversocket and continue to listen for the client connection or disconnection (including connection timeout) that is not determined. 2. The server side should be an information send center, and all client information is transmitted to the server side, and the server is distributed by the server.

The above is the two main two tasks of the server. It is not difficult to see that the task of the server is not complicated.

The work that the client should do includes:

1. Establish a communication channel with the server to send information to the server. 2. Receive information from the server.

For the server, the client's task is simpler. With the simple analysis of the above, you can know that the above four problems have completed the core of the chat system.

Further analyze the system structure. . .

After completing the above analysis, it is started to study each problem.

The first is the listening of the server side. Since the server side needs to communicate with multiple clients, the system's part must have to complete with multiple threads. Once the server finds a new client to establish a connection, immediately establish a thread and the client. Communication. The advantage of multi-thread is that multiple communication connections can be handled simultaneously without the delay or loss of the data queuing, and the performance of the system can be used well.

Complete the first task of the server side, then the second task is not difficult to solve. The above has been established for each connected client. This thread is better than a telephone line to wait for the client, and the information send center is equivalent to a total station. Once someone calls in, it will pass the telephone line. The information is transmitted to the bus, and then this information is sent to the receiving group as needed. This means that every time the server receives a message, the method of the information sending center is called, and the information is sent to all clients (or a particular / a few clients).

Let's take a look at the client. Since the client needs to receive information and send information at the same time, multiple threads must also be utilized. The main thread is used to receive the content input by the user and send it to the server side, and a background thread will always receive information from the server side and returns it to the client. In this way, the chat system of a Server-Client structure is basically completed.

Implementation. . .

First create a Server class, the Server class completes a listening work and adds thread to the client to establish a connection:

Public class server {

Static socket socketlist [] = new socket [1000];

Public Server (int solidketport) throws ioException {

ListenForConnecting (socketport);

}

// listenforconnecting method Used to listen to connection private void listenforconnecting (int socketport) throws oews oException {

Serversocket Serversocket = New Serversocket (Socketport);

// The key is the part of the listener, with a while loop to realize

While (true) {

Socket socket = serversocket.accept ();

/ / Once the client is connected in, add a thread to communicate with the client, the key is to transfer parameters, // transmit the SOKCET of the Server class and the client to this communication thread.

New ConnectionForClient (this, socket);

}

// sendMessageCenter method is used to send information to the client

Public void sendMessageCenter (String Message, Socket Socket) THROWS IOException {

// Establish an output stream, send the information to the client // You will find an array socketlist for the storage of client socket information, which updates the data when the client // is connected or disconnected, not detailed here. Discuss this problem

For (int K = 0; k

DataoutputStream DataOut = New DataOutputStream (SocketList [k] .getoutputstream ());

DataOut.writeutf (Message);

// Other procedures for judging the information ...

....

}

The ConnectionForClient class is then created. This class completes the connection to the client and communicates with it:

Public Class ConnectionForClient Extends Thread {

Server Server; Socket Socket;

// All preparations are completed in the constructor

Public ConnectionForClient (Server Server, Socket Socket) {

THIS.SERVER = Server; this.socket = Socket;

START ();

}

Public void run () {

// First establish the DataInputStream class to receive information sent by the client

DataInputStream DataIn = New DataInputStream (Socket.getInputStream ()); // is similar to the server's listening connection work, the same listening to the information sent by the client

While (true) {

String message = datain.readutf ();

// Once the information sent by the client is received, the detailed sender and the sending information are transmitted to the Server class of the Server. SsendMessageCenter (MSSAGE, this.socket);

}

}

Static public void main (string args []) throws exception {

// Program start execution

INT SocketPort = 8765;

New Server (socketport);

}

}

Complete the server's program, then the client:

Public class client extends thread {

DataInputstream DataIN; DataOutputstream Data;

// Client class constructor PUBLIC Client (String Host, Int port) {

Establish Socket Socket = New Socket (Hostadress, Socketport);

// Establish an input and output flow object DataIn = New DataInputStream (Socket.getInputStream ()); DataOut = New DataOutputStream (Socket.getOutputStream ());

// Start the background thread for listening to the information of the server-side transmission.

// Then start receiving the user input information and transmitted to the client

BufferedReader IN = New BufferedReader (NEW INPUTSTREAMREADER (System.in);

String Words = "";

While (true) {

Words = in.readline ();

SendMessage (Words);

}

}

Public void run () {

While (true) {

// Waiting for the server to send information and display it

String message = datain.readutf ();

System.out.print (Message "/ n>");

}

// sendMessage method Sends the user input to the server

Private void sendmessage (string message) {

DataOut.writeutf (Message);

}

// Program start executing public static void main (string args []) {

INT SocketPort = 8765;

String hostdress = "211.211.211.211" / / It can actually specify IP and port through parameters, simplify this process here

New Client (Hostadress, Socketport);

}

In this way, the core of a Server-Client structure is complete, of course, this is just a simplest framework. If further improvement is further improved, there will be many problems, for example:

other problems. . .

The information sent by the client should be divided into public and private information, then SendMessageCenter determines which users should send information according to the category of information. The client with permissions can dynamically establish a chat channel, then SendMessageCenter can also determine the chat channel to which the information belongs is decided to send information.

The client can perform chat commands, such as returning online information of the current server, returning to a user's related information, exiting chat system, etc.

All of these issues can be done through the Client's SendMessageCenter method for the Server class to complete it. A communication protocol is a set of conventions, which makes relevant information to make the recipient and sender know that this information will communicate as an identity.

For example, when the information sent by the sender is normal chat information, it can increase a prefix: Words = "[chatmessage] words, and send another prefix words =" [ReturnonLineList "when sending a message to return online list ].

When the sendMessageCenter receives client information, first determine the prefix of the Message, if "[chatmessage]" is transmitted to other clients, if "[ReturnonLineLIST] is returned to the client an onlineLINELIST.

Generally, this has developed a simple communication protocol.

Regarding the chat system, it is probably such an experience. The code above the specific implementation ignores some details and the necessary try-catch-finally structure, the purpose is to make the core code look more clearly. You can discuss better structural design.

转载请注明原文地址:https://www.9cbs.com/read-23156.html

New Post(0)