This article starting number public Java cat said & uncle blog | MySelf, reproduced please stated the source.

preface

First of all for a simple chat room, we should have a certain concept, here we omit the user module to explain, but simply talk about the chat room first several functions: self-dialogue, friends exchange, group chat, offline message, etc..

Today’s demo will help us do just that!!

The framework

Our entire Demo basically does not require you to spend too much time, can implement the above several functions.

First, we need to introduce the framework we are going to adopt today, InChat: a lightweight and efficient asynchronous network application communication framework that supports multi-end (application and hardware Iot). With this framework, we basically need only two or three classes to implement the functionality we need today.

Need to know about SSM & SpringBoot?

InChat itself does not rely on any underlying framework, so anyone who knows the basic Java language can implement their own WebSocket chat room.

Frame manual

For detailed instructions, please refer to the inchat version 1.1.0 instructions on the official website

Start Demo Construction

Build an empty Maven project

We don’t need to rely on other Maven packages, just the framework mentioned in this article.

com.github.UncleCatMySelfInChat11.. 0-alpha
Copy the code

Docking two interfaces with implementations

One is provided by the framework for our users to save and read data. Through the implementation of this interface, we can get the communication data of each chat asynchronously. The InChatMessage here is a framework custom communication object.

public class ToDataBaseServiceImpl implements InChatToDataBaseService{

    @Override
    public Boolean writeMapToDB(InChatMessage message) {
        System.out.println(message.toString());
        return true; }}Copy the code

There is also an interface to verify login (we are dealing with user login and verification module, so return true), and another interface to return group chat array information.

public class verifyServiceImpl implements InChatVerifyService {


    @Override
    public boolean verifyToken(String token) {
        // Login verification
        return true;
    }

    @Override
    public JSONArray getArrayByGroupId(String groupId) {
        // Get the group chat member ID according to the group chat ID
        JSONArray jsonArray = JSONArray.parseArray("[\" 1111 \ ", \ "2222 \" and \ "3333 \"]");
        returnjsonArray; }}Copy the code

We can say in more detail that to obtain group chat information, we can obtain the corresponding user Id array through a groupId, and we can make a data query by ourselves.

Core framework startup code

Just go to the code, and then we’ll talk about it.

public class DemoApplication {

	public static void main(String[] args) {
		// Configure the InChat configuration factory
		ConfigFactory.inChatToDataBaseService = new ToDataBaseServiceImpl();
		ConfigFactory.inChatVerifyService = new verifyServiceImpl();
		// InChat starts by default
		InitServer initServer = new InitServer(new InitNetty());
		initServer.open();

		// Get the user value
		WebSocketChannelService webSocketChannelService = new WebSocketChannelService();

		// Start a new thread
		new Thread(new Runnable() {
			@Override
			public void run(a) {
				// Set the default server send value
				Map map = new HashMap<>();
				map.put("server"."Server");
				// Get the user Token that the console user wants to send
				Scanner scanner = new Scanner(System.in);
				String token = scanner.nextLine();
				// Get the user connection
				Channel channel = (Channel) webSocketChannelService.getChannel(token);
				// Call the interface to sendwebSocketChannelService.sendFromServer(channel,map); } }).start(); }}Copy the code

Ok, the above has basically completed our chat room Demo, is not very simple! ?

First, we configure the two classes we implement into the framework’s configuration factory, and then we start the framework, and the relevant classes are provided by the framework. The following thread is a framework interface to the server in the first person to send notification messages to the user, enter “1111”, Demo Demo user token value.

On the front

InChat: a lightweight and efficient asynchronous network application communication framework that supports multi-terminal (application and hardware Iot). You can directly come to the project to obtain the front page, or directly visit the address: github.com/UncleCatMyS…

For this front-end page, we need to change the IP address.

Run the debug project

Next, start the back-end project directly, and when we see the following message, the project has started successfully.

INFO - Server started successfully [192.168.1.121:8090]Copy the code

The IP address here needs to be replaced with the following IP address after reader startup.

Then directly use the browser to open the chat. HTML page can be, about the method of JS, you can see the InChatV1.1.0 version instructions.

The running effect is as follows:

INFO - the server startup success [192.168.1.121:8090] the DEBUG - Dio.net ty. Buffer. Bytebuf. CheckAccessible:trueDEBUG - Loaded default ResourceLeakDetector: Io.net ty. Util. ResourceLeakDetector @ 68 ad4247 INFO - [DefaultWebSocketHandler. ChannelActive] / 192.168.1.121:17330 links the DEBUG success  - -Dio.netty.recycler.maxCapacityPerThread: 4096 DEBUG - -Dio.netty.recycler.maxSharedCapacityFactor: 2 DEBUG - -Dio.netty.recycler.linkCapacity: 16 DEBUG - -Dio.netty.recycler.ratio: 8 DEBUG - [id: 0xabb0dbad, L:/192.168.1.121:8090 -r :/192.168.1.121:17330] WebSocket Version V13 Server Handshake DEBUG - WebSocket Version 13 server handshake key: JYErdeATDgbPmgK0mZ+IlQ==, response: YK9ZiJehNP+IwtlkpoVkPt94yWY= DEBUG - Decoding WebSocket Frame opCode=1 DEBUG - Decoding WebSocket Frame length=31 INFO -  [DefaultWebSocketHandler.textdoMessage.LOGIN] DEBUG - Encoding WebSocket Frame opCode=1 length=33 DEBUG - Decoding WebSocket Frame opCode=1 DEBUG - Decoding WebSocket Frame length=43 INFO - [DefaultWebSocketHandler textdoMessage. SENDME] the DEBUG - 1111 Encoding WebSocket Frame opCode = 1 length = 28 INFO - "asynchronous write data" InChatMessage{time=Mon Dec 24 10:03:00 CST 2018,type='sendMe', value=' ', token='1111', groudId='null', online='null', onlineGroup=null, one='null'} DEBUG - Decoding WebSocket Frame opCode=1 DEBUG - Decoding WebSocket Frame length=56 INFO - [DefaultWebSocketHandler textdoMessage. SENDTO] the DEBUG - 1111 Encoding WebSocket Frame opCode = 1 length = 41 INFO - "asynchronous write data" InChatMessage{time=Mon Dec 24 10:03:01 CST 2018,type='sendTo', value=' ', token='1111', groudId='null', online='2222', onlineGroup=null, one='2222'} DEBUG - Decoding WebSocket Frame opCode=1 DEBUG - Decoding WebSocket Frame length=60 INFO - [DefaultWebSocketHandler.textdoMessage.SENDGROUP] 1111 DEBUG - Encoding WebSocket Frame opCode=1 length=59 INFO - InChatMessage{time=Mon Dec 24 10:03:02 CST 2018,type='sendGroup', value=' ', token='1111', groudId='2', online='null', onlineGroup=[2222, 3333], one='null'}
1111
DEBUG - Encoding WebSocket Frame opCode=1 length=22
Copy the code

Public number: Java cat said

Now architecture designer (code farmer) and entrepreneurial technology consultant, unruly mediocre, love open source, talk about program life and irregular dry goods.