Code example of Android chat function based on socket.io

1、 Brief description

Socket.io is a cross platform open source framework that is fully implemented by JavaScript, based on node.js and supports websocket protocol for real-time communication. It includes JavaScript on the client side and node.js on the server side.

This kind of official introduction seems a little silly. In short, the client can establish a real-time communication pipeline with the server through socket.io

2、 Apply

This section introduces the laying, communication and destruction of socket.io communication pipeline.

2.1 introducing socket.io package

2.2 instantiating socket objects

Server address (this address is the official test address of socket.io. Please change it in the actual project):

Instantiate the socket object according to the server address:

Options are some configuration parameters that can be selected by the user. Some configurations are as follows:

2.3 registered listening

Here, we need to register some listening events to listen to some behaviors generated during socket communication. For example, the following is the listening callback after registering a successful socket connection:

2.4 establishing connections through socket objects

So far, our pipeline laying work has been completed. Next, we only need to turn on the switch of the pipeline, so that the client and server can communicate and trust each other:

How do we know if the connection between the two has been successful? Yes, we registered listening in 2.3. Once the socket connection is successful, the callback will be triggered. At this time, we can handle it according to the actual needs of the project.

2.5 simple use

At this point, if we want to send a message to the server, how do we implement it? Socket.io provides the following operations:

You can also do this:

2.6 destruction of pipelines

When we don't want to use the pipeline anymore, we need to destroy the pipeline. Very simple, we just need to disconnect and log off the monitoring:

Well, the whole communication process of socket.io is completed. For us, is it easy to use.

3、 Complete source code

I don't know if this part is popular (ha ha ~), the source code is based on the official server address of socket.io and combined with the actual project. It has strong scalability. It is specially shared for your reference.

Android chat based on socket.io

Finally, thank you for coming. Congratulations on sticking to the end. If there is anything wrong with the article and source code, please correct it.

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>