Home >Web Front-end >H5 Tutorial >Implement websocket chat room using html5 websocket_html5 tutorial skills

Implement websocket chat room using html5 websocket_html5 tutorial skills

WBOY
WBOYOriginal
2016-05-16 15:48:341874browse

What is websocket

The WebSocket protocol is a new protocol introduced by html5. Its purpose is to achieve full-duplex communication between the browser and the server. Students who read the link above must have already understood how to do this in the past with low efficiency and high consumption (polling or comet). In the websocket API, the browser and server only need to perform a handshake action, and then, A fast channel is formed between the browser and the server. Data can be transmitted directly between the two. Doing this at the same time has two benefits

1. Reduced communication transmission bytes: Compared with the previous use of http to transmit data, websocket transmits very little additional information. According to Baidu, it is only 2k

2. The server can actively push messages to the client without the client having to query

The concepts and benefits are everywhere on the Internet, so I won’t go into details. Let’s take a brief look at the principles and then start writing a web version of the chat room.

Shake hands

In addition to the three-way handshake of the TCP connection, in the websocket protocol, the client and the server need an additional handshake to establish a connection. In the latest version of the protocol, it looks like this

The client sends a request to the server Send request


Copy code
The code is as follows:

GET / HTTP/1.1
Upgrade: websocket
Connection: Upgrade
Host: 127.0.0.1:8080
Origin: http:/ /test.com
Pragma: no-cache
Cache-Control: no-cache
Sec-WebSocket-Key: OtZtd55qBhJF2XLNDRgUMg==
Sec-WebSocket-Version: 13
Sec-WebSocket-Extensions: x-webkit-deflate-frame
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36

The server responds

Copy the code
The code is as follows:

HTTP/ 1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: xsOSgr30aKL2GNZKNHKmeT1qYjA=

The "Sec-WebSocket-Key" in the request is random , the server will use these data to construct a SHA-1 information digest. Add the magic string "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" to "Sec-WebSocket-Key". Use SHA-1 encryption, then BASE-64 encoding, and return the result to the client as the value of the "Sec-WebSocket-Accept" header (from Wikipedia).

websocket API

After the handshake, the browser and the server establish a connection, and the two can communicate with each other. The API of websocket is really simple. Take a look at the W3C definition


Copy the code
The code is as follows:

enum BinaryType { "blob", "arraybuffer" };
[Constructor(DOMString url, optional (DOMString or DOMString[]) protocols)]
interface WebSocket : EventTarget {
readonly attribute DOMString url;

// ready state
const unsigned short CONNECTING = 0;
const unsigned short OPEN = 1;
const unsigned short CLOSING = 2;
const unsigned short CLOSED = 3;
readonly attribute unsigned short readyState;
readonly attribute unsigned long bufferedAmount;

// networking
attribute EventHandler onopen;
attribute EventHandler onerror;
attribute EventHandler onclose;
readonly attribute DOMString extensions;
readonly attribute DOMString protocol;
void close([Clamp] optional unsigned short code, optional DOMString reason);

// messaging
attribute EventHandler onmessage;
attribute BinaryType binaryType;
void send(DOMString data);
void send(Blob data);
void send(ArrayBuffer data);
void send(ArrayBufferView data);
};

Create websocket

Copy code
The code is as follows:

ws=new WebSocket(address); //ws://127.0.0.1:8080


Call its constructor and pass in the address to create A websocket, it is worth noting that the address protocol must be ws/wss

Close socket

Copy code
The code is as follows:

ws.close();


웹 서비스를 닫으려면 웹 서비스 인스턴스의 close() 메서드를 호출하세요. 물론 웹 서비스가 닫힌 이유를 설명하는 코드와 문자열을 전달할 수도 있습니다.

여러 콜백 함수 핸들

비동기 실행으로 인해 콜백 함수는 당연히 필수입니다.

onopen: 연결이 생성된 후 호출됩니다.
onmessage: 서버 메시지를 받은 후 호출됩니다. .
onerror: 오류가 발생할 때 호출됩니다.
onclose: 연결을 닫을 때 호출됩니다.

이름을 보면 그 기능을 알 수 있습니다. 각 콜백 함수는 Event 개체를 전달하며 메시지는 event.data를 통해 액세스할 수 있습니다.

API 사용

소켓을 성공적으로 생성한 다음 콜백 함수에 값을 할당할 수 있습니다


코드 복사
코드는 다음과 같습니다. 다음과 같습니다:

ws=new WebSocket(address);
ws.onopen=function(e){
var msg=document.createElement('div');
msg.style.color='#0f0';
msg.innerHTML="서버 > 연결이 열려 있습니다.";
msgContainer.appendChild(msg);
ws.send('{<' 문서 .getElementById('name').value '> }');

이벤트 바인딩을 사용할 수도 있습니다.

복사 code
코드는 다음과 같습니다:

ws=new WebSocket(address);
ws.addEventListener('open',function(e){
var msg=document.createElement('div') ;
msg.style.color='#0f0';
msg.innerHTML="서버 > 연결이 열려 있습니다.";
msgContainer.appendChild (msg);
ws.send('{ <' document.getElementById('name').value '>}');

클라이언트 측 구현
사실 클라이언트 측 구현은 웹소켓과 관련된 몇몇 문장을 제외하면 비교적 간단합니다. 자동 포커스, 키 입력 이벤트 처리, 자동 위치 지정 등 몇 가지 간단한 기능이 있습니다. 메시지박스는 하단에 하나씩 설명하지 않겠습니다

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn