Implementation of network communication chat room based on java TCP

Posted by Xiphoid8 on Wed, 19 Jan 2022 01:03:27 +0100

1.1 Preface

In today's information society, with the rapid development of the network, people rely more and more on the network and are more and more inseparable from the network. As a result, there are more and more chat tools, such as MSN and QQ. The development of chat systems such as online chat is changing with each passing day. Therefore, the idea of making an online chat tool similar to QQ came into being, And by making the program, we can better learn the knowledge of network software programming. The purpose of network programming is to communicate with other computers directly or indirectly through network protocol. There are two main problems in network programming. One is how to accurately locate one or more hosts on the network, and the other is how to reliably and efficiently transmit data after finding the hosts. In the TCP/IP protocol, the IP layer is mainly responsible for the positioning of network hosts,

The route of data transmission. A host on the Internet can be uniquely determined by the IP address. TCP layer provides application-oriented reliable or unreliable data transmission mechanism, which is the main object of network programming. Generally, it does not need to care about how IP layer processes data. At present, the more popular network programming model is client

/Server (C/S) structure. That is, one of the communication parties acts as a server waiting for the customer to make a request and respond. Customers apply to the server when they need services.

Generally, the server always runs as a daemon and listens to the network port. Once there is a customer request, it will start a service process to respond to the customer. At the same time, it will continue to listen to the service port so that subsequent customers can also get a response service.

1.2 design requirements

The goal of this course design is to use socket () to design a chat program. The program is based on C/S mode. The client machine sends a chat request to the server, and the server answers and can display the information sent by the client.

1.3 design purpose

By designing a network chat program, I have a detailed understanding and full understanding of socket, datagram communication, URL and urlconnectionom. Can only apply relevant to relevant practice.

1.4 function realization

The chat room is divided into client and server,

The server program is mainly responsible for listening to messages sent by the client,

The client needs to log in to the corresponding server to realize the normal chat function.

The main functions of the server are

1) Listen on a specific port and wait for the client to connect

2) The user can configure the listening port of the server (3) to send system messages to customers who have connected to the server

5) Disconnect all users when the service is stopped

Main functions of client

1) Connect to the server that has enabled the chat service

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 connection

4) When the server is turned on. Users can log in at any time

5) Users can send messages to everyone or one person

1.5 knowledge base

The java knowledge points applied are:

1. Thread

Thread pool, thread startup, interface, etc. Both client and server use threads

2. Socket

socket is used for port monitoring and data transmission

new Socket("localhost",port);

3. Swing graphical

Simple buttons, input boxes, pop ups, etc

4. Data flow

Character stream wrapper, buffered character output stream wrapper

PrintWrite(new OutputStream(new socket(".."),"UTF-8"),true)

Part code:

Define the server-side interface and add event listening and event processing. Call the start class Socket method to realize the online and offline listening of server users, and call the Socket class to realize the sending and receiving of messages on the server.

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
 * @author Li Yangyong
 *
 */
public class Server {
	//The Socket running on the server is used to receive the connection from the client. 
	private ServerSocket server;
	//Thread pool
	private ExecutorService threadPool;
	//A shared collection that holds all client output streams
	private List<PrintWriter> allOut;
	
	/**
	 * Constructor to initialize the server
	 */
	public Server(){
		try {
			/*
			 * Initialize shared collection
			 */
			allOut = new ArrayList<PrintWriter>();
			
			/*
			 * Read configuration file
			 * java.util.Properties
			 * 
			 */
			Properties properties = new Properties();
			/*
			 * void load(InputStream in)
			 * This method is used to read the data in a given stream and then parse it
			 * 
			 * We can use FileInputStream to read our data
			 * Defined configuration file config Properties, so we can
			 * Create the stream and pass it as a parameter to the load method.
			 * In this way, the Properties can be read through FileInputStream
			 * Our profile.
			 */
			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 equal sign in the configuration file, you can obtain the corresponding
			 * value
			 * serverport=8088
			 */
			String port = properties.getProperty("serverport");
			System.out.println("Service port:"+port);
			/*
			 * When initializing ServerSocket, you need to pass in a parameter
			 * This parameter is the service port opened by the server
			 * The client connects with 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 threads in thread pool:"+threadCount);
			
			/*
			 * Initialize thread pool
			 */
			threadPool = Executors.newFixedThreadPool(Integer.parseInt(threadCount));
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * Add an output stream to the shared collection
	 * @param out
	 */
	public synchronized void addOut(PrintWriter out){
		allOut.add(out);
	}
	/**
	 * Deletes the given output stream from the shared collection
	 * @param out
	 */
	public synchronized void removeOut(PrintWriter out){
		allOut.remove(out);
	}
	/**
	 * Traverse all output streams in the shared collection and send the given message to all users
	 * Client for
	 * @param message
	 */
	public synchronized void sendMessageToAllClient(String message){
		for(PrintWriter out : allOut){
			out.println(message);
		}
	}
	
	
	
	/**
	 * Method for server to start working
	 */
	public void start(){
		try {
			/*
			 * Socket accept()
			 * This method is that ServerSocket starts listening to port 8088
			 * Is a blocking method until a client connects, if the client
			 * When connected, a Socket will be returned, which is used to connect with
			 * To communicate with this client.
			 */
			while(true){
				System.out.println("Waiting for a client connection...");
				Socket socket = server.accept();
				System.out.println("A client is connected!");
				
				/*
				 * Start a thread and connect the Socket of the client just connected
				 * Pass it 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 internal class serves the server. Used to communicate with a client
	 * Interactive.
	 * @author Li Yangyong
	 */
	class ClientHandler implements Runnable{
		/*
		 * The Socket of the client that this thread uses to interact with
		 */
		private Socket socket;
		/*
		 * The nickname of the client
		 */
		private String nickName;
		
		public ClientHandler(Socket socket){
			this.socket = socket;
			/*
			 * Get the address information of the remote computer
			 */
			InetAddress address = socket.getInetAddress();
			//Gets the address of the remote computer
			String add = address.getHostAddress();
			System.out.println(add+"It's online!");
			
		}
		
		public void run() {
			PrintWriter pw = null;
			try {
				/*
				 * Get the output stream through the Socket, which is used to send messages to
				 * client
				 */
				OutputStream out = socket.getOutputStream();
				OutputStreamWriter osw
							= new OutputStreamWriter(out,"UTF-8");
				pw = new PrintWriter(osw,true);
				
				//Put the client's output stream into a shared collection
				addOut(pw);
				
				/*
				 * InputStream getInputStream()
				 * Socket This method is used to obtain the data sent by the remote computer
				 */
				InputStream in = socket.getInputStream();
				
				InputStreamReader isr
							= new InputStreamReader(in,"UTF-8");
				
				BufferedReader br = new BufferedReader(isr);
				/*
				 * First read a line of string, because the first string sent by the client
				 * The line string is the nickname of the client. After reading it, set it to
				 * On property nickName
				 */
				nickName = br.readLine();
				
				/*
				 * Broadcast, the user is online
				 */
				sendMessageToAllClient("["+nickName+"]It's online");
				
				
				//Read a line of string sent by the client
				/*
				 * Use the readLine method of BufferedReader to read the data sent by the client
				 * When a line of string comes over, due to the operating system used by the client
				 * Different, here, after the client is disconnected from the server, the method is
				 * The reaction is different.
				 */
				String message = null;
				while((message = br.readLine())!=null){
					//Forward 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 inform all clients that the user is offline
				sendMessageToAllClient("["+nickName+"]Offline.");
				/*
				 * Close the socket of the client.
				 * When you close the socket, you will use the input stream it gets to
				 * The output stream is turned off.
				 */
				try {
					socket.close();
				} catch (IOException e) {
				}
			}
			
		}
		
	}
	
}



Screenshot of function implementation:

Start the server service first:

Then start the client:

client can start multiple

Such a simple chat room based on Java TCP simulation is completed

Course summary:

Through this course design, I have a deeper understanding of network communication knowledge. Deepen the understanding of the specific connection process of TCP/UDP protocol. At the same time, I have a full understanding of socket, datagram communication, URL and urlconnectionom. And apply this knowledge to specific cases. This course design not only applies the knowledge of sockets, but also applies GUI programming in Java, and applies various components and layouts in the design framework. Through the design of server and client main framework, we have a clearer understanding of various components and layouts in GUI programming. Successfully apply the knowledge learned in books to practice. Through this course design, I have reviewed and applied the knowledge of Swing components, panel containers, event processing, thread creation and synchronization, input and output processing, internal classes, exception handling, and network communication learned in Java. Cultivate their own programming ability and combine learning with practice. In the process of learning Java, the program can often be understood by yourself, but when you need to apply the learned knowledge to practice, you often encounter such problems. This course design has greatly exercised your hands-on ability, and also made yourself understand that only hands-on can turn the knowledge in the textbook into your own. Only by participating in practice can we find problems, 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 hands-on.

Code acquisition:

java TCP network communication chat room (source code + report paper 6000 words)

Wonderful push of relevant Java practical projects

Design and implementation of epidemic prevention system based on java ssm springboot+VUE

Design and implementation of front and back office of film ticketing website management system based on java springboot+mybatis

Design and implementation of spring boot + mybatis winery internal management system based on Java SSM

Design and implementation of smart life sharing platform based on JAVA springboot+mybatis

Design and implementation of furniture mall platform based on Java springboot+vue+redis

Design and implementation of anti epidemic substance information management system based on JAVA SSM springboot

See more bloggers' homepage and more practical projects > > >

Well, that's all for today. Let's praise, collect and comment. Let's start three times with one button. See you next time~~

Topics: Java socket thread pool tcp