Written before:
Maybe it's the end of the period, and various course designs are coming one after another. Recently, I saw two questions and answers on CSSDN, which is to write a socket-based chat program. I happened to have done something with socket recently. Out of interest, I took a few nights of free time to knock one. Currently, it only supports single chat, group chat, and file transfer functions. First, I posted an ugly program image (UI is written in java swing, I have forgotten this one for a long time, so I couldn't help but read the JDK API to write one), as shown below:
Server design:
The server has two main operations: one is to block the socket of the receiving client and perform response processing, and the other is to detect the heartbeat of the client. If the client does not send a heartbeat for a period of time, remove the client, create the ServerSocket, and then start two thread pools to handle these two things (newFixedThreadPool, newScheduledThreadPool). The corresponding processing classes are SocketDispatcher and SocketSchedule. The SocketDispatcher is distributed to different SocketHandlers according to different socket requests. SocketWrapper adds a shell wrapper to the socket, and records the latest interaction time of the socket with the SocketHolder stores the socket collection that currently interacts with the server. The design is as follows:
Client design:
Client design is mainly divided into two parts, namely socket communication module design and UI related design
The design of client socket communication is actually similar to that of server. The difference is that the server receives heartbeat packets, while the client sends heartbeat packets. Since the client only communicates with one server (the communication between clients is also distributed by the server), only a thread pool of size 2 is used to handle these two things (newFixedThreadPool(2)). The corresponding processing classes are ReceiveListener and KeepAliveDog. When the ReceiveListener is initialized, a Callback is sent as a callback to the client receives the server message. The default implementation of Callback is DefaultCallback. DefaultCallback is distributed to different handlers through HF according to different events. ClientHolder stores the current client information. The design is as follows:
UI related design, I don’t plan to write the UI by myself. After all, what I wrote is too ugly, so I may ask my classmates or friends to help me knock it later, so I hand over the UI event processing to Action to handle it, and simply separate the UI design and event response. All UIs inherit JFrame and implement the View interface. The Handler implementation class above is obtained through Router (it will be returned directly if it exists, and it will be created and stored if it does not exist). The View provides the UI creation(), obtain container(), get the components in the UI getComponent(), display display(), and recycle trash(); ResultWrapper and ResultHolder are just for creating and storing chat tabs.
Common module design:
The Common module is mainly data interaction, where JSON data is used for interaction. The common module defines various types of interaction information, the transmission of socket information implemented by SendHelper, I18N is the language, and ConstantValue is the configuration and constants in the system (the constants are all interfaces, which may not be very good). For ReturnMessage, it has a series of DTOs as its content attributes.
Program entry:
Finally, the entrance program for the server and client is given (the complete code is hung on csdn, and it will be updated continuously if you have time, and the article will have an address at the end)
Server portal:
package yaolin.chat.server;import java.io.IOException;import java.net.ServerSocket;import java.util.Date;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.ScheduledExecutorService;import java.util.concurrent.TimeUnit;import yaolin.chat.common.ConstantValue;import yaolin.chat.util.LoggerUtil;/** * Server* @author yaolin */public class Server { private final ServerSocket server; private final ExecutorService pool; public Server() throws IOException { server = new ServerSocket(ConstantValue.SERVER_PORT); pool = Executors.newFixedThreadPool(ConstantValue.MAX_POOL_SIZE); } public void start() { try { ScheduledExecutorService schedule = Executors.newScheduledThreadPool(1); // Watch dog. Exception?? schedule.scheduleAtFixedRate(new SocketSchedule(), 10, ConstantValue.TIME_OUT, TimeUnit.SECONDS); while (true) { pool.execute(new SocketDispatcher(server.accept())); LoggerUtil.info("ACCEPT A CLIENT AT " + new Date()); } } catch (IOException e) { pool.shutdown(); } } public static void main(String[] args) { try { new Server().start(); } catch (IOException e) { LoggerUtil.error("Server start failed! -> " + e.getMessage(), e); } }} Client portal:
package yaolin.chat.client;import java.io.IOException;import javax.swing.JOptionPane;import yaolin.chat.client.callback.DefaultCallback;import yaolin.chat.client.view.Router;import yaolin.chat.client.view.impl.RegisterAndLoginView;/** * * @author yaolin * */public class NiloayChat { public static void main(String[] args) { RegisterAndLoginView v = (RegisterAndLoginView) Router.getView(RegisterAndLoginView.class).create(); try { v.display(); Client client = new Client(new DefaultCallback()); client.start(); ClientHolder.setClient(client); } catch (IOException e) { JOptionPane.showMessageDialog(v.getContentPane(), e.getMessage()); } }} Source code download: demo
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.