Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Introduction and Application of HTML5 Web Sockets

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article introduces the introduction and application of HTML5 Web Sockets, the content is very detailed, interested friends can refer to, hope to be helpful to you.

A cool new feature in HTML 5 is Web Sockets

This paper introduces how to run Web Socket on the server side of the PHP environment, create a client and send and receive server-side information through the Web Sockets protocol.

What is Web Sockets?

Web Sockets is a two-way communication technology in a (TCP) interface, PUSH technology type. At the same time, Web Sockets will still be based on W3C standards, and so far, Chrome and Safari's * * versions of browsers already support Web Sockets.

What will Web Sockets replace?

Web Sockets can replace Long Polling (PHP server-side push technology), which is an interesting concept. The client sends a request to the server. Now, the server does not respond to the unprepared data, it will keep the connection open until the data is ready to be sent, and then the client receives the data and sends another request.

This has its benefits: it reduces the latency of any connection, and there is no need to create a new connection when one connection is already open. But Long-Polling is not a fancy technology, it is still possible to request a pause, so a new connection will need to be established.

Some Ajax applications use these techniques-this is often due to low resource utilization. Imagine what a great thing it would be if the server booted itself in the morning and sent data to clients that wanted to receive it without having to establish some connection ports in advance. Welcome to the world of PUSH technology!

* step: fix the Web Socket server

The article will focus more on client-side creation than server-side execution and so on. The author uses XAMPP based on Windows 7 to implement local running PHP.

Start the Apache server

Step 2: modify URLs and port

To modify the server based on your previous installation, here is an example from setup.class.php:

Public function _ _ construct ($host='localhost',$port=8000,$max=100) $this- > createSocket ($host,$port)

Browse the file and make changes where appropriate.

Step 3: start creating the client

Let's create a basic template, which is my client.php file:

Web Sockets Client Web Sockets Client e.g. Try 'hi',' name', 'age',' today'

Disconnect

We have created the basic template: a chat log container, an input input box, and a disconnected button.

Step 4: add some CSS

There is no fancy code, just deal with the style of the label.

Body {font-family:Arial, Helvetica, sans-serif;} # container {border:5px solid grey; width:800px; margin:0 auto; padding:10px;} # chatLog {padding:5px; border:1px solid black;} # chatLog p {margin:0;} .event {color:#999 } .warning {font-weight:bold; color:#CCC;}

Step 5: Web Socket event

First, let's try and understand the concept of Web Socket events:

◆ onopen: when the interface is up

◆ onmessage: when you receive a message

◆ onclose: when the interface is down

How can we achieve this? First create the Web Socket object.

Var socket = new Web Socket ("ws://localhost:8000/socket/server/startDaemon.php")

Then detect the event as follows:

Socket.onopen = function () {alert ("Socket has been opened!");}

When we receive a message, we do this:

Socket.onmessage = function (msg) {alert (msg); / / Awesome!}

But we still try to avoid using alert, and now we can integrate what we have learned into the client page.

Step 6: JavaScript

First we put the code into the document.ready function of jQuery, and then we check to see if the user's browser supports Web Socket. If not, we will add a link to the Chrome browser page.

$(document) .ready (function () {if (! ("Web Socket" in window)) {$('# chatLog, input, button, # examples'). FadeOut ("fast"); $('

Oh no, you need a browser that supports Web Sockets. How about Google Chrome?

'). AppendTo (' # container');} else {/ / The user has Web Sockets connect (); function connect () {/ / the connect function code is below})

As you can see, if the user's browser supports Web Socket, we will execute the connect () function. Here are the core functions, and we will begin to create open, close, and receive events. We will define URL on our server.

Var socket; var host = "ws://localhost:8000/socket/server/startDaemon.php"

You may find that there is no http in URL. Well, yes, this is a Web Socket URL that uses a different protocol. The following is an illustration of URL decomposition:

Let's move on to the connect () function and put the code in the try/catch block so that if there is something wrong with the code, we can let the user know. We create the Web Socket and pass the information to the message () function, which we'll explain later. We create our onopen, onmessage and onclose functions. It is important to note that we provide the user with port status, which is not required, but we put it in mainly to facilitate debugging.

CONNECTING = 0 OPEN = 1 CLOSED = 2 function connect () {try {var socket; var host = "ws://localhost:8000/socket/server/startDaemon.php"; var socket = new Web Socket (host); message ('Socket Status:' + socket.readyState) Socket.onopen = function () {message ('Socket Status:' + socket.readyState+' (open)');} socket.onmessage = function (msg) {message ('Received:' + msg.data) } socket.onclose = function () {message ('Socket Status:' + socket.readyState+' (Closed)');}} catch (exception) {message ('

Error'+exception);}}

The message () function is simple enough to fill the chat log container with the text we want to present to the user. We make a paragraph (in the socket event function)

) tag to create the appropriate class, we have only one paragraph closing tag in the message function.

Function message (msg) {$('# chatLog') .append (msg+')

');}

Current results

If you have followed the above tutorial step by step, good, we have created HTML/CSS templates, created and established Web Socket connections, and kept users up to date by creating connections.

Step 7: send data

Now we have the submit button, but we also need to listen to the event when the user presses the keyboard and run the send function. The'13 'below is the ASCII code corresponding to the enter key.

$('# text') .keypress (function (event) {if (event.keyCode = = '13') {send ();}})

Here is the send () function:

Function send () {var text= $('# text'). Val (); if (text== "") {message ('Please enter a message'); return;} try {socket.send (text); message (' Sent:'+ text)} catch (exception) {message ('Error:' + exception) } $('# text') .val ("")

Here's what we need:

Socket.send ()

The extra code does the following work: checking whether the user has entered nothing but still clicks back, empties the input input box, and executes the message () function.

Step 8: turn off Socket

Turning off the Socket operation is fairly simple, as long as you add click event listeners to the disconnect button.

$('# disconnect') .click (function () {socket.close ();})

Complete JavaScript code

$(document) .ready (function () {if (! ("Web Socket" in window)) {$('# chatLog, input, button, # examples'). FadeOut ("fast"); $('

Oh no, you need a browser that supports Web Sockets. How about Google Chrome?

AppendTo ('# container');} else {/ / The user has Web Sockets connect (); function connect () {var socket; var host = "ws://localhost:8000/socket/server/startDaemon.php"; try {var socket = new Web Socket (host) Message ('Socket Status:' + socket.readyState); socket.onopen = function () {message ('Socket Status:' + socket.readyState+' (open)');} socket.onmessage = function (msg) {message ('Received:' + msg.data) } socket.onclose = function () {message ('Socket Status:' + socket.readyState+' (Closed)');}} catch (exception) {message ('

Error'+exception);} function send () {var text= $('# text'). Val (); if (text== "") {message ('Please enter a message'); return } try {socket.send (text); message ('Sent:' + text)} catch (exception) {message ('');} $('# text'). Val (") } function message (msg) {$('# chatLog') .append (msg+')

);} $('# text') .keypress (function (event) {if (event.keyCode = = '13') {send ();}}); $(' # disconnect') .click (function () {socket.close () }); / / End connect} / / End else})

Step 9: run the Web Socket server

We need to enter some command lines, and XAMPP provides a more convenient shell option. Click the 'shell' button of the XAMPP control panel and enter:

Php-Q path\ to\ server.php

Now you have the Web Socket server running!

The great task has been completed!

When the page is read, an attempt is made to create a Web Socket connection, and then the user can enter information and receive it from the server. You can learn about the dynamics of HTML 5 Web Socket through The Web Socket API.

This is the end of the introduction and application of HTML5 Web Sockets. I hope the above content can be helpful to everyone and learn more knowledge. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report