In the recent computer network class, the teacher began to talk about socket,tcp related knowledge, then the brain popped an idea, that is to create a chat room. Implementation is also quite a lot, the common can be used in C + + or Java socket programming to build such a chat room. Of course, I did not hesitate to choose node to write, node has a framework called Socket.io has been very well encapsulated socket related API, so whether it is learning or use is very easy to get started, it is highly recommended here! Demo has been done and put on my personal site, we can try, it is fun.
Go in and try-http://www.yinxiangyu.com:9000 (adapted the example provided by the Socket.io official)
Source-Https://github.com/yxy19950717/js-practice-demo/tree/master/2016-4/chat
Before combing through the demo, take a look at the principle things that the chat room is built for.
What is a socket
The first step is to make it clear how the Web chat client communicates with the server. Yes, it is the socket (socket) that is responsible for such communications. for example, if you are using your computer to browse the page and have 1 telnet and an SSH session open, then you have 3 application processes. When the Transport layer (TCP,UDP) in your computer receives data from the underlying network layer, it needs to direct the received data to one of the three processes. Each process has one or more sockets , which is the equivalent of a portal that passes data from the network to the process and passes data from the process to the network.
For example, at the receiving end, the Transport layer examines the field in the message segment, identifies the receiving socket, and then directs the message to the socket. This work of transporting the data in the beginning section to the correct socket is called multi-channel decomposition . Similarly, the source host collects data blocks from different sockets and encapsulates the first piece of information for each data (for decomposition) to generate a segment of the packet, which is then passed to the network layer, which is called multiplexing.
WebSocket and HTTP
Understanding the basic principle of socket sockets, you can know that the socket is always not the application layer of things, it is connected to the application layer and the transport layer of a bridge, that from the perspective of implementation, we should be how to write a chat room such an application?
HTTP is a stateless protocol, what is a stateless state? This means that the HTTP server does not hold any information about the customer. Because TCP provides a reliable data transfer service for HTTP, it means that each HTTP request message sent by a client process is fully reachable to the server. The stateless nature of HTTP stems from a layered architecture, and its advantages are obvious, without worrying about data loss. However, this behavior can occur when the server sends the requested file to the customer without storing any status information about the customer. That is, when a client requests the same file two times a time, the server does not respond because it has just provided the file for the customer, and theHTTP does not remember what had been done before !
Of course, in traditional HTTP applications, the client and server side sometimes need to communicate over a long period of time, usually with a cookie to authenticate the communication, and long time to maintain a connection, will be time and bandwidth, so that the performance is not very good, and the chat room need is real-time communication, So we need to websocket such a deal. (Some browsers also do not support WebSocket, and in the case of not very real-time, still can use the HTTP Ajax way to communicate).
WebSocket is a new protocol for HTML5, which is primarily designed to address the pressure on the server for Ajax polling and long poll. In HTTP, polling through Ajax and long poll is constantly listening to the server for new messages, and in WebSocket, it is pushed whenever the server has new messages, and it can stay connected to the proxy server (typically Nginx or Apache) for a long time. But unlike HTTP, it only needs a single request to stay connected.
For the framework of Socket.io, it is compatible with the use of WebSocket and HTTP two protocols, and the Ajax polling method is used for message exchange in some browsers that cannot use the WebSocket protocol.
If you want to learn more about WebSocket, you can read this article: WebSocket What is the principle? Why can I make persistent connections?
Using Socket.io
Socket.io is a fully JavaScript-based, node. js, WebSocket-enabled protocol for real-time communication, a cross-platform, open source framework that includes both client-side JavaScript and node. js on the server. In addition to supporting the WebSocket communication protocol, Socket.io supports many kinds of polling (Polling) mechanisms as well as other real-time communication methods, and encapsulates the generic interface, and implements the corresponding code for these real-time mechanisms on the server side. The polling communication mechanism implemented by Socket.io includes Adobe Flash sockets, Ajax long polling, Ajax multipart streaming, persistent iframe, JSONP polling, and more. Socket.io can automatically choose the best way to implement network real-time application according to the browser's support to communication mechanism.
With such a framework, you will be very easy to get started with the understanding of socket programming. Socket.io's API can be learned on the following two websites
Github:https://github.com/socketio/socket.io
Official website: http://socket.io/docs/
To create a chat room app, first determine the number of event responses that the server in the chat needs to receive, divided into the following points:
1. When a new user comes in (' Add user ')
2. When the user is typing (' typing ')
3. When the user stops typing (' Stop typing ')
4. When a user sends a message (' New message ')
5. When the user leaves (' disconnect ')
Next is the event response that the client user (s) needs to receive:
1. I came in (' login ')
2. Someone came in (' User joined ')
3. Someone is typing (' typing ')
4. Someone stopped the input (' Stop typing ')
5. Someone sent a new message (' new ')
6. Someone left (' User Ieft ')
Next we need to use the socket's on and emit interface to write, server-side code is as follows:
Index.js:
View Code
On the client side, there must also be a script that receives the Send message
Main.js:
View Code
Understanding the socket operation is only a matter of focusing on the Socket.on,socket.broadcast.emit functions. Socket.on provides a method for receiving a message, and after receiving it, the second parameter is the callback function, and Socket.broadcast.emit is the broadcast send, sending an object or a string to each user. Here you may think Socket.io is very simple, of course, this is just some of its features, more usage you can learn by yourself.
The example just provided is adapted to the official instance of Socket.io, where bloggers add avatar selection to the front-end interface and change the layout of the first person's third-person text, so the code can be a bit cumbersome in main.js ( so just focus on the socket.) ), complete code on my github download:socket.io public chat room
Finally, welcome everyone boring time to my chat room chat Oh!
Create a public chat room with Socket.io