PHP teaches you five minutes to write a real-time bullet screen website

Source: Internet
Author: User
Tags php language

Nowadays, with the rapid development of the Internet era, such as the current fire of the live platform has real-time barrage scrolling, and small series first to fix is the front page, at least there is a box, then the problem, these video barrage website how to do real-time synchronization? How does PHP develop a similar website?

After searching, a jQuery.danmu.js open source project was found. Look at star, it's kinda github.com/chiruom/jquery.danmu.js.

Go to the demo directory, first run the example to see the results.

Sure enough, the point after the emergence of a tall on the page, a little bit of a look at the function is quite many. But the question comes, why do I click Start, a little reaction also wood has it.

Find out why ING.

It turned out to be a problem with the jquery plugin in the source file. In the SRC directory, there is no such file

<scriptsrc= ". /src/jquery-2.1.4.min.js "></script>

Forget it or call Baidu's online jquery plugin.

<scriptsrc= "Http://libs.baidu.com/jquery/2.1.4/jquery.min.js" ></script>

Another refresh, not expected, to run successfully.

Back end, let's talk about the principle of the barrage. The barrage, which is equivalent to a public chat room, is a client sends a message to the server, and the server then broadcasts the received message to other clients.

Polling with the traditional Ajax? No, this efficiency is too low, think of the big hot live platform are tens of thousands of people online, thousands people at the same time, if you rely on Ajax polling a PHP interface server will be unbearable. And the bomb screen message storage scheme is slightly complex, someone asked why to store it? Because the HTTP protocol used by Ajax is a stateless protocol, there is no flag between a client and B client for the server, and if the server wants to make sure that a client and the B client are requesting only two requests, the server returns only those two clients that have not obtained the barrage messages. Then the server side must use a cache to identify which one client has seen the barrage message. In summary Ajax can achieve small-scale missile screen communication scheme, but very troublesome.

Fortunately, the latest HTML5 in the WebSocket protocol, we can websocket this HTTP protocol based on the real-time communication protocol to replace the traditional Ajax I asked you to answer the old communication mode. And we are phper, for this kind of people who only know PHP how to write WebSocket server? Fortunately, we also know that PHP has a swoole extension, we use it in the PHP language can be very convenient to build a websocket server.

On Swoole, the following is the official website:

PHP's asynchronous, parallel, high-performance network communication engine, written in pure C, provides the PHP language for asynchronous multithreaded servers, asynchronous TCP/UDP network clients, asynchronous MySQL, asynchronous Redis, database connection pooling, Asynctask, Message Queuing, millisecond timers, Asynchronous file read-write, asynchronous DNS query. Swoole built-in Http/websocket server side/client, Http2.0 server side.

Swoole can be widely used in the Internet, mobile communications, enterprise software, cloud computing, online games, Internet of Things (IoT), car networking, smart home and other fields. The use of Php+swoole as a network communication framework can greatly improve the efficiency of enterprise IT research and development teams and focus on the development of innovative products.

There is one more problem to solve, which is that this jquery.danmu.js is a plug-in based on the runtime of the barrage. Then how to do it in real time. What bloggers want to do is to specify a time on the server (that is, their connection time), and when there is a client connection, return the current timestamp of the server, and then start the timing based on this. However, the following problems are encountered:

The bullet-screen plug-in is a very second-timing system.

The running time of JS timer on each browser is slightly different.

Time cannot be fully synchronized.

WebSocket is real-time communication, hey, that all the client time, inconsistency is inconsistent, the time of the bomb screen according to the various clients, all the time to send the current client, WebSocket only pass the data does not contain the time (well, a bit around, I feel that I was spared), Let's go straight to the code.

<! Doctypehtml>

<metacharset= "Utf-8" >

<metaname= "Viewport" content= "width=device-width,initial-scale=1.0" >

<title> Bullet Screen Madebydiligentyang</title>

<style>

body{

font-family: "Microsoftyahei"!important;

Font-color: #222;

}

pre{

Line-height:2em;

font-family: "Microsoftyahei"!important;

}

h4{

Line-height:2em;

}

#danmuarea {

position:relative;

Background: #222;

width:800px;

height:445px;

Margin-left:auto;

Margin-right:auto;

}

. center{

Text-align:center;

}

. ctr{

Font-size:1em;

Line-height:2em;

}

</style>

<scriptsrc= "Http://libs.baidu.com/jquery/2.1.4/jquery.min.js" ></script>

<scriptsrc= ". /dist/jquery.danmu.min.js "></script>

<bodyclass= "Center" >

Demo<br><br>

<!--black background and barrage area--

<divid= "Danmuarea" >

<divid= "Danmu" >

</div>

</div>

<!--control Area--

<divclass= "Ctr" >

<buttontype= "button" onclick= "pauser" > Screen pause </button>

<buttontype= "button" onclick= "Resumer" > Barrage continue </button>

Display the barrage: <inputtype= ' checkbox ' checked= ' checked ' id= ' ishide ' value= ' is ' onchange= ' changehide ' >

Transparency of the projectile screen:

<inputtype= "Range" name= "Op" id= "Op" onchange= "Op" value= "><br>"

Current screen runtime (seconds): <spanid= "Time" ></span>

<!--set current bounce time (seconds): <inputtype= "text" id= "Set_time" max=20/>

<buttontype= "button" onclick= "SetTime" > Settings </button>-->

<br>

Bomb screen:

<selectname= "COLOR" id= "Color" >

<optionvalue= "White" > Black </option>

<optionvalue= "Red" > Red </option>

<optionvalue= "green" > Greens </option>

<optionvalue= "Blue" > Blue </option>

<optionvalue= "Yellow" >xxx</option>

</select>

<selectname= "Size" id= "Text_size" >

<optionvalue= "1" > Big text </option>

<optionvalue= "0" > Small text </option>

</select>

<selectname= "position" id= "position" >

<optionvalue= "0" > Scrolling </option>

<optionvalue= "1" > Top </option>

<optionvalue= "2" > Bottom </option>

</select>

<inputtype= "textarea" id= "text" max=300/>

<buttontype= "button" onclick= "send" > Send </button>

</div>

<script>

WebSocket

Varwsserver= ' ws://123.206.61.229:9505 ';

Varwebsocket=newwebsocket (WSServer);

Websocket.onopen=function (evt) {

Console.log ("Connectedtowebsocketserver.");

/Websocket.send ("Gaga"); /

Open the barrage after you connect.

$ (' #danmu '). Danmu (' Danmuresume ');

};

Websocket.onclose=function (evt) {

Console.log ("Disconnected");

};

Websocket.onmessage=function (evt) {

Console.log (' retrieveddatafromserver: ' +evt.data);

vartime=$ (' #danmu '). Data ("Nowtime") +1;

Vartext_obj=evt.data+ ', ' time ': ' +time+ '} ';//Get plus current

Console.log (Text_obj);

Varnew_obj=eval (' (' +text_obj+ ') ');

$ (' #danmu '). Danmu ("Adddanmu", new_obj);//Add barrage

};

Websocket.onerror=function (evt,e) {

Console.log (' erroroccured: ' +evt.data);

};

Initialization

$ ("#danmu"). Danmu ({

left:0,

top:0,

Height: "100%",

Width: "100%",

speed:20000,

Opacity:1,

Font_size_small:16,

Font_size_big:24,

top_botton_danmu_time:6000

});

A timer to monitor the reload time and update to the page

functiontimedcount{

$ ("#time"). Text ($ (' #danmu '). Data ("Nowtime"));

T=settimeout ("Timedcount", 50)

}

Timedcount;

functionstarter{

$ (' #danmu '). Danmu (' Danmustart ');

}

functionpauser{

$ (' #danmu '). Danmu (' Danmupause ');

}

functionresumer{

$ (' #danmu '). Danmu (' Danmuresume ');

}

functionstoper{

$ (' #danmu '). Danmu (' danmustop ');

}

functiongetime{

Alert ($ (' #danmu '). Data ("Nowtime"));

}

functiongetpaused{

Alert ($ (' #danmu '). Data ("paused"));

}

Send the bullet screen, using the method recommended in document README.MD section 7th

functionsend{

Vartext=document.getelementbyid (' text '). Value;

Varcolor=document.getelementbyid (' color '). Value;

Varposition=document.getelementbyid (' position '). Value;

vartime=$ (' #danmu '). Data ("Nowtime") +1;

Varsize=document.getelementbyid (' text_size '). Value;

Vartext_obj= ' {"text": "' +text+ '", "Color": "' +color+ '", "Size": "' +size+ '", "position": "' +position+ '", "time": ' + Time+ '} ';

In order to deal with the simple, convenient follow-up time, and isnew, first jiangzi hair half.

Note: Time for the bomb screen out of the times, isnew for whether to add a frame, their own bomb screen, the common sense is a border.

Vartext_obj= ' {"text": "' +text+ '", "Color": "' +color+ '", "Size": "' +size+ '", "position": "' +position+ '";

Send with WebSocket

Websocket.send (Text_obj);

Clear the appropriate content

document.getElementById (' text '). value= ';

}

Adjust the transparency function

functionop{

Varop=document.getelementbyid (' op '). Value;

$ (' #danmu '). Danmu ("SetOpacity", op/100);

}

Hide Show

functionchangehide{

Varop=document.getelementbyid (' op '). Value;

op=op/100;

if (document.getElementById ("Ishide"). Checked) {

$ ("#danmu"). Danmu ("SetOpacity", 1)

}else{

$ ("#danmu"). Danmu ("SetOpacity", 0)

}

}

Set the time of the bomb screen

functionsettime{

Vart=document.getelementbyid ("Set_time"). Value;

T=parseint (t)

$ (' #danmu '). Danmu ("SetTime", t);

}

</script>

</body>

The above code should pay attention to the establishment and reception of WebSocket, as well as the processing of the bomb screen in the Send method.

ws_server.php

<?php

Creating WebSocket server objects, listening on 0.0.0.0:9505 ports

$ws =newswoole_websocket_server ("0.0.0.0", 9505);

Monitoring WebSocket Connection Open Event

$ws->on (' Open ', function ($ws, $request) {

Var_dump ($request->fd, $request->get, $request->server);

Equivalent to recording a log bar, with connection time and connection IP

Echo$request->fd. ' -----time: '. Date ("Y-m-dh:i:s", $request->server[' request_time '). ' --ip--'. $request->server[' remote_addr ']. ' -----‘;

});

Listening for WebSocket message events

$ws->on (' message ', function ($ws, $frame) {

Record received messages, can be written to the log file

echo "message:{$frame->data}\n";

Traverse all connections, loop broadcast

foreach ($ws->connectionsas$fd) {

If it is a client, you can add the IsNew attribute to your own hair, otherwise you will not add

if ($frame->fd== $fd) {

$ws->push ($frame->fd, $frame->data, "isnew": "" ');

}else{

$ws->push ($FD, "{$frame->data}");

}

}

});

Monitoring WebSocket Connection shutdown events

$ws->on (' Close ', function ($ws, $FD) {

echo "client-{$fd}isclosed\n";

});

$ws->start;

How to run:

Enter phpws_server.php to start the server-side WebSocket first. If you want to run in the background without disconnecting the user terminal, you need to create a log.txt to access the above output, and then enter nohupphpws_server.php>log.txt&.

Note, if you want to use this item, you need to modify your server IP address yourself. Only need to modify varwsserver= ' ws://123.206.61.229:9505 ', office, the background code does not need to do any processing.

PHP teaches you five minutes to write a real-time bullet screen website

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.