“This is my 28th day of participating in the First Challenge 2022. For details: First Challenge 2022
1.1 introduction
In today’s information society, the network rapid development, more and more people rely on to the network, more and more inseparable from the network , as a chat tools, more and more, like MSN, QQ, network chat chat system such as the development of the day The new moon, so had to make a similar network QQ chat tools, And through making the program can also better learn network software programming knowledge. The purpose of network programming is to communicate directly or indirectly with other computers through network protocols. There are two main problems in network programming, one is how to accurately locate one or more hosts on the network, the other is how to reliably and efficiently transmit data after finding the hosts. In TCP/IP protocol, the IP layer is mainly responsible for locating network hosts.
A route for data transmission that uniquely identifies a host on the Internet by its IP address. The TCP layer provides application-oriented reliable or unreliable data transmission mechanism, which is the main object of network programming, and generally does not need to care about how the IP layer deals with data. The more popular network programming model is the client
/ Server (C/S) structure. That is, the two sides of the communication as a server to wait for customers to request and respond. Customers request services from the server when they need them.
The server is always running as a daemon, listening to the network port. Once a customer requests it, it will start a service process to respond to the customer. At the same time, it continues to listen to the service port, so that subsequent customers also get the service response.
1.2 Design Requirements
The goal of this course is to design a chat program using socket (). The program is based on C/S mode. The client machine sends a chat request to the server, and the server responds and displays the message sent by the client.
1.3 Design Purpose
By designing a network chat program, have a detailed understanding and full understanding of sockets, datagram communications, urls, and relevant knowledge of URLConnectiom. What is relevant is to apply it to relevant practice.
1.4 Function Implementation
The chat room is divided into two parts: client side and server side.
The server program listens for messages from clients,
The client must log in to the corresponding server to implement the normal chat function.
The main functions of the server are
1) Listen on a specific port and wait for the customer to connect
2) You can configure the listening port of the server. 3) You can send system messages to customers connected to the server
5) Disconnect all users when the service is stopped
Main functions of the client
1) Connect to the server where the chat service is enabled
2) You can configure the IP address and port number of the server to be connected
3) Users can configure the user name displayed after the connection
4) When the server is on. Users can log in at any time
5) Users can send messages to all or one person
1. 5* * * *Knowledge base
Java knowledge points applied to the following:
- Thread the Thread
Thread pools, thread startup, interfaces, etc. Threads are used on both the client and the server
- Socket
Socket is used for port monitoring and data transfer
new Socket("localhost",port);
Copy the code
- The Swing graphical
Simple buttons, input boxes, pop boxes, etc
- The data flow
Character stream wrap, buffered character output stream wrap,
PrintWrite(new OutputStream(new socket(".." ),"UTF-8"),true)Copy the code
Part code:
Define server-side interfaces to add event listening and event handling. Call the start class Socket method to realize the server user online and offline listening, call the Socket class to realize the server side of the message receiving and receiving.
package chat;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/** * chat room server *@authorYang Yong Li * */
public class Server {
// The Socket running on the server is used to receive client connections.
private ServerSocket server;
/ / thread pool
private ExecutorService threadPool;
// A shared collection of all client output streams
private List<PrintWriter> allOut;
/** * constructor, used to initialize the server */
public Server(a){
try {
/* * Initializes the shared collection */
allOut = new ArrayList<PrintWriter>();
/* * Read the configuration file * java.util.properties * */
Properties properties = new Properties();
/* * void load(InputStream in) * We can use the FileInputStream stream to read our config file config.properties, so we can create the stream and pass it as an argument to the Load method. Properties can then read our configuration file via FileInputStream. * /
FileInputStream fis
= new FileInputStream("config.properties");
properties.load(fis);
// Get the server port number
/* * String getProperty(String key) * Given the content on the left of the medium number of the configuration file, you can obtain the corresponding * value * ServerPort =8088 */
String port = properties.getProperty("serverport");
System.out.println("Service port :"+port);
/* * A parameter is passed to initialize the ServerSocket. * This parameter is the service port that the server opens externally. */ The client connects to the server through this port
server = new ServerSocket(Integer.parseInt(port));
/* * Get the number of threads assad */
String threadCount
= properties.getProperty("threadcount");
System.out.println("Number of thread pool threads :"+threadCount);
/* * Initializes the thread pool */
threadPool = Executors.newFixedThreadPool(Integer.parseInt(threadCount));
} catch(Exception e) { e.printStackTrace(); }}/** * adds an output stream * to the shared collection@param out
*/
public synchronized void addOut(PrintWriter out){
allOut.add(out);
}
/** * Removes the given output stream * from the shared collection@param out
*/
public synchronized void removeOut(PrintWriter out){
allOut.remove(out);
}
/** * iterates through all output streams in the shared collection, sending the given message to all * clients *@param message
*/
public synchronized void sendMessageToAllClient(String message){
for(PrintWriter out : allOut){ out.println(message); }}/** * how the server starts working */
public void start(a){
try {
/* * Socket accept() * The ServerSocket starts listening on port 8088. This method blocks until a client connects. Returns a Socket that is used to communicate with the client. * /
while(true){
System.out.println("Waiting for a client connection...");
Socket socket = server.accept();
System.out.println("A client is connected!");
/* * Starts a thread and passes it the Socket * of the newly connected client to handle the interaction with the client. * /
ClientHandler clientHandler
= new ClientHandler(socket);
// Thread t = new Thread(clientHandler);
// t.start();threadPool.execute(clientHandler); }}catch(Exception e) { e.printStackTrace(); }}public static void main(String[] args) {
Server server = new Server();
server.start();
}
/** * This inner class is for the server. Used to interact with a client. *@authorYang-yong li * /
class ClientHandler implements Runnable{
/* * The Socket the thread uses to interact with the client */
private Socket socket;
/* * The client's nickname */
private String nickName;
public ClientHandler(Socket socket){
this.socket = socket;
/* * Get the address information of the remote computer */
InetAddress address = socket.getInetAddress();
// Get the address of the remote computer
String add = address.getHostAddress();
System.out.println(add+"Online!");
}
public void run(a) {
PrintWriter pw = null;
try {
/* * Gets the output stream through the Socket, which is used to send the message to the * client */
OutputStream out = socket.getOutputStream();
OutputStreamWriter osw
= new OutputStreamWriter(out,"UTF-8");
pw = new PrintWriter(osw,true);
// Banishes the client's output into the shared collection
addOut(pw);
/* * InputStream getInputStream() * This Socket method is used to fetch data from a remote computer */
InputStream in = socket.getInputStream();
InputStreamReader isr
= new InputStreamReader(in,"UTF-8");
BufferedReader br = new BufferedReader(isr);
/* * * select * * from the client and set it to */ 'nickName'
nickName = br.readLine();
/* * The user is online */
sendMessageToAllClient("["+nickName+"] Online");
// Read a string sent from the client
/* * BufferedReader's readLine method reacts differently when the client disconnects from the server, depending on the operating system on which the client is operating. * /
String message = null;
while((message = br.readLine())! =null) {// Forwards the read content to all clients
sendMessageToAllClient(nickName+"Say:"+message); }}catch (Exception e) {
} finally{
// Remove the client's output stream from the shared collection
removeOut(pw);
// broadcast to all clients that the user is offline
sendMessageToAllClient("["+nickName+"] Offline.");
/* * Close the socket for the client. Closing the socket also closes the input stream and the output stream. * /
try {
socket.close();
} catch (IOException e) {
}
}
}
}
}
Copy the code
Function implementation screenshot:
Start the server first:
Then start client:
Multiple clients can be started
Such a simple Chat room based on Java TCP emulation is complete
Course Summary:
Through this course design, I have a deeper understanding of the knowledge of network communication. This helps you understand the TCP/UDP connection process. At the same time, I have a thorough understanding of socket, datagram communication, URL, and URLConnectiom. And apply this knowledge to specific cases. This course design not only applies the knowledge of sockets, but also applies the GUI programming in Java, and applies various components and layouts in the design framework. Through the design of the main framework of server and client, we have a clearer understanding of various components and layouts in GUI programming. Put what you have learned in books into practice successfully. Through this course design, I have learned Swing components in Java, panel container, event processing, thread creation, synchronization, input and output processing, internal classes, exception processing, and network communication knowledge with a review and application. I have cultivated my programming ability and combined learning with practice. In the process of learning Java, often procedures to understand, but need to apply the knowledge to practice, tend to encounter such and such problems, this course design has greatly exercised their hands-on ability, but also make themselves understand that only hands-on will be the knowledge on the textbook into their own. Only by participating in practice, can we discover and solve problems and improve our ability in the process of solving problems. I hope I can combine theory with practice more in the future, and then improve my programming ability and software design ability in the process of getting started.
In general, this project is relatively simple and excellent, suitable for beginners as a reference for course design and graduation design