Written in front:
It's probably near the end of the term. A variety of curriculum design, recently seen in the Csdn 2 of the same question and answer, that is to write a socket based chat program, just recently with a socket to do some things, out of interest, I smoked a few nights of free time to knock A, currently only support single chat, group chat, Files transfer these features. First, put out an ugly program (the UI is written in Java swing, which has long forgotten, helpless to see the JDK API), as shown in the following figure:
Service-Side design:
The service side has two main operations, one is to block the receiving client socket and do response processing, the second is to detect the heartbeat of the client, if the client has not sent a heartbeat over a period of time to remove the client, created by the server ServerSocket, Then start two thread pools to handle the two (Newfixedthreadpool,newscheduledthreadpool), the corresponding processing classes are Socketdispatcher, Socketschedule, The socketdispatcher is distributed to different sockethandler according to different requests of the socket, while the socketwrapper adds a layer of shell packing to the socket. Use Lastalivetime to record the most recent interaction time for the socket, Socketholder store the socket collection currently interacting with the server. The design is as follows:
Client design:
The client design is divided into two parts, which are socket communication module design and UI-related design respectively.
Client socket communication design, the design is actually similar to the design of the service side, the difference is that the server is to receive heartbeat packets, and the client is to send a heartbeat packet, because the client only with a server to communicate (communication between the client is also distributed by the server), So here we only use a 2-size thread pool to handle these two things (Newfixedthreadpool (2)), and the corresponding processing classes are Receivelistener, Keepalivedog, Where Receivelistener in the initialization of a callback as the client received the service side of the callback, callback default implementation is Defaultcallback, Defaultcallback is distributed to different handler according to different events, while Clientholder stores the current client information, designed as follows:
UI-related design, I'm not going to write my own UI here, after all, I write it too ugly, so later may ask a classmate or friend to help knock, so I will be the UI event processing by action to handle, the UI design and event response simple separation, all UI inheritance JFrame and implementation view interface , the handler implementation class above provides the UI creation (), gets container (), Gets the component Getcomponent () from the UI (), acquires the router (), and obtains the components in the Ui,view () Displays display (), reclaims Trash (), Resultwrapper and Resultholder just to create and store chat tabs.
Common Module Design:
The common module is mainly data interaction, where the JSON data is used to interact, the common module defines various kinds of interactive information, sendhelper the socket information that is implemented, i18n is the language word, Constantvalue is the configuration and constants in the system (where constants are interfaces, which may not be good), for ReturnMessage has a series of DTO as its content attribute.
Program Entry:
Finally gives the server and the client's entry program (complete code hangs on the CSDN, has the time to update continuously, the article finally has the address)
Service-Side entry:
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 (), 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 (); The 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 Download: Demo
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.