WebSocket
WebSocket in a Web environment enables connection-oriented full duplex communication, as with a TCP socket. (The server and browser can send and receive data real-time through a continuously connected TCP line.)
The difference between the previously used communication method in the Web environment and the new Web socket lies in the protocol. The Web socket protocol uses HTTP in establishing a connection, however, all communication after the connection is established happens using the Web socket's independent protocol.
With a Web socket, the used header is extremely small, causing very little overhead. A long-term connection is used as a basis, meaning that if there is connection, sending data from client or server is possible. The long-term connection means that data can be sent and received through 1 connection, and you do not need to establish a separate connection for each sending and receiving instance. Ping and pong frames can also be used.
The main features of the WebSocket API include:
- Connecting to a server
To connect to a server, you must create a WebSocket interface with the socket server URL as a mandatory parameter. The URL format has some restrictions, for example, it must use the ws or wss protocol. If the URL is not valid or uses a wrong protocol, a syntax error occurs.
If the connection with the socket server succeeds, the readyState attribute value is set to 1. If the connection fails the attribute value is set to 3, and the HTTP 503 error is returned.
When the connection is no longer needed, you can close the connection with the close() method.
- Sending data
By using the send() method of theWebSocket interface, you can send data to the server. The data is transmitted using the established connection. If the readyState attribute value is CONNECTING, the method throws an InvalidStateError exception.
- Receiving data
You can receive data from the server through the message event.