webrtc:call_学习WebRTC:构建实时井字游戏

这篇博客介绍了如何利用WebRTC技术构建实时井字游戏。通过使用PubNub进行信令服务,确保浏览器兼容性,并详细阐述了视频设置、游戏实现、拨打和接听电话的步骤。文章还涉及到了DataChannel API在游戏交互中的应用。此外,提供了关于测试和调试的注意事项,以及如何在实际应用中处理兼容性和连接问题。
摘要由CSDN通过智能技术生成

webrtc:call

The Scotchmas Day 3 giveaway can be found at the end of this article.

在本文的末尾可以找到Scotchmas Day 3赠品

Time to show off the versatility of WebRTC. If you don't know it already, WebRTC is a free, open project that provides simple APIs for creating Real-Time Communications (RTC) for browsers and mobile devices. It makes streaming any content such as video, audio, or arbitrary data simple and fast!

是时候炫耀WebRTC的多功能性了。 如果您还不了解WebRTC,则它是一个免费的开放项目,其中提供了用于为浏览器和移动设备创建实时通信(RTC)的简单API。 它使流式传输任何内容(例如视频,音频或任意数据)变得简单, 快捷

header

PubNub用于信令。 (PubNub for Signaling.)

WebRTC is not a standalone API, it needs a signaling service to coordinate communication. Metadata needs to be sent between callers before a connection can be established.

WebRTC不是独立的API,它需要信令服务来协调通信。 建立连接之前,需要在调用者之间发送元数据。

This metadata includes things such as:

此元数据包括以下内容:

  • Session control messages to open and close connections

    会话控制消息以打开和关闭连接
  • Error messages

    错误讯息
  • Codecs/Codec settings, bandwidth and media types

    编解码器/编解码器设置,带宽和媒体类型
  • Keys to establish a secure connection

    建立安全连接的钥匙
  • Network data such as host IP and port

    网络数据,例如主机IP和端口

Once signaling has taken place, video/audio/data is streamed directly between clients, using WebRTC's PeerConnection API. This peer-to-peer direct connection allows you to stream high-bandwidth robust data. In addition, we will be using DataChannels to stream messages through our RTC connection.

发出信号后,即可使用WebRTC的PeerConnection API在客户端之间直接传输视频/音频/数据。 通过对等直接连接,您可以流式传输高带宽的健壮数据。 另外,我们将使用DataChannels通过RTC连接流式传输消息。

PubNub makes this signaling incredibly simple, and then gives you the power to do so much more with your WebRTC applications.

PubNub使此信令变得异常简单,然后使您能够使用WebRTC应用程序执行更多操作。

浏览器兼容性 (Browser Compatibility)

WebRTC is widely adopted by popular browsers such as Chrome and Firefox, but there are many browsers on which certain features will not work. See a list of supported browsers here.

WebRTC被流行的浏览器(例如Chrome和Firefox)广泛采用,但是在许多浏览器上某些功能无法使用。 在此处查看支持的浏览器列表。

第1部分:视频设置 (Part 1: The Video Setup)

Time to begin! First, I will show you how to make the bare minimum WebRTC video chat. Then, in Part 2 we will be using the WebRTC DataChannel API to play TicTacToe. The live demo for this tutorial can be found here!

该开始了! 首先,我将向您展示如何进行最低限度的WebRTC视频聊天。 然后,在第2部分中,我们将使用WebRTC DataChannel API播放TicTacToe。 可以在这里找到本教程的现场演示!

关于测试和调试的注意事项 (A Note on Testing and Debugging)

If you try to open file://<your-webrtc-project> in your browser, you will likely run into Cross-Origin Resource Sharing (CORS) errors since the browser will block your requests to use video and microphone features. To test your code you have a few options. You can upload your files to a web server, like Github Pages if you prefer. In production, WebRTC requires HTTPS, so if you choose this method, visit your pages as https://yourusername.github.io/project.

如果尝试在浏览器中打开file://<your-webrtc-project> ,则由于浏览器将阻止您使用视频和麦克风功能的请求,因此您可能会遇到跨域资源共享(CORS)错误。 要测试您的代码,您有几种选择。 您可以根据需要将文件上传到Web服务器,例如Github Pages 。 在生产中,WebRTC需要HTTPS,因此,如果选择此方法,请以https://yourusername.github.io/project访问页面。

However, to keep development local, I recommend you setup a simple server using Python.

但是,为了使开发保持本地化,我建议您使用Python设置一个简单的服务器。

To so this, open your terminal and change directories into your current project and depending on your version of Python, run one of the following modules.

为此,请打开终端并将目录更改为当前项目,然后根据您的Python版本,运行以下模块之一。

cd <project-dir>

# Python 2
python -m SimpleHTTPServer <portNo>

# Python 3
python -m http.server <portNo>

For example, I run Python2.7 and the command I use is python -m SimpleHTTPServer 8001. Now I can go to http://localhost:8001/index.html to debug my app! Try making an index.html with anything in it and serve it on localhost before you continue.

例如,我运行Python2.7,而我使用的命令是python -m SimpleHTTPServer 8001 。 现在,我可以转到http://localhost:8001/index.html调试我的应用程序! 尝试制作包含任何内容的index.html并将其提供给localhost后再继续。

步骤1:HTML5骨干网 (Step 1: The HTML5 Backbone)

<div id="tic-tac-box" style="float: left; width: 47%;"></div>
<div style="float: left; width: 50%;">
    <div id="video-chat" hidden="true">
        <div id="vid-box"></div>
        <button onclick="end()">End Call</button>
    </div>
    <form name="loginForm" id="login" action="#" onsubmit="return login(this);">
            <input type="text" name="username" id="username" placeholder="Enter A Username"/>            
            <input type="submit" name="login_submit" value="Log In">
    </form>
    <form name="callForm" id="call" action="#" onsubmit="return makeCall(this);">
        <input type="text" name="number" id="call" placeholder="Enter User To Call!"/>
        <input type="submit" value="Call">
    </form>
</div>

This should leave you with a very basic HTML backbone that looks something like this:

这应该为您提供一个非常基本HTML主干,看起来像这样:

html

The tic-tac-box div will house our game board, and video-chat is where we will place our WebRTC video stream. I use style="float: left; width: 50%" to align our video chat and game side by side.

tic-tac-box div将容纳我们的游戏板, video-chat是我们放置WebRTC视频流的地方。 我使用style="float: left; width: 50%"将我们的视频聊天和游戏并排对齐。

步骤2:JavaScript导入 (Step 2: The JavaScript Imports)

There are three libraries that you will need to include to make WebRTC operations much easier. The first thing you should include is jQuery to make modifying DOM elements a breeze. Then, you will need the PubNub JavaScript SDK to facilitate the WebRTC signaling. Finally, include the PubNub WebRTC SDK which makes placing phone calls as simple as calling the dial(number) function.

您需要包括三个库,以使WebRTC操作更加容易。 您应该包括的第一件事是jQuery ,使修改DOM元素变得轻而易举。 然后,您将需要PubNub JavaScript SDK来简化WebRTC信令。 最后,包括PubNub WebRTC SDK,该SDK使拨打电话就像调用Dial dial(number)函数一样简单。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://cdn.pubnub.com/pubnub.min.js"></script>
<script src="https://cdn.kevingleason.me/webrtc-2.0.0.js"></script>
<script src="https://cdn.kevingleason.me/tictactoe.js"></script>

The tictactoe.js is a basic game implementation I found online and modified to make this tutorial easy. It has functions to mark squares and reset the game.

tictactoe.js是我在网上找到的基本游戏实现,并对其进行了修改,以tictactoe.js本教程。 它具有标记方块和重置游戏的功能。

Now we are ready to write our calling functions for login, makeCall, and end!

现在,我们可以编写用于loginmakeCallend调用函数了!

第3部分:拨打和接听电话 (Part 3: Making and Receiving Calls)

In order to start facilitating video calls, you will need a publish and subscribe key. To get your pub/sub keys, you’ll first need to sign up for a PubNub account. Once you sign up, you can find your unique PubNub keys in the PubNub Developer Dashboard. The free Sandbox tier should give you all the bandwidth you need to build and test your WebRTC Application.

为了开始进行视频通话,您需要一个发布和订阅密钥。 要获取发布/ 订阅密钥,您首先需要注册一个PubNub帐户 。 注册后,您可以在PubNub开发人员仪表板中找到唯一的PubNub键。 免费的沙盒层应为您提供构建和测试WebRTC应用程序所需的所有带宽。

var video_hold = document.getElementById("video-chat");
var video_out  = document.getElementById("vid-box");

function login(form) {
    user_name = form.username.value || "Anonymous";
    var phone = window.phone = PHONE({
        number        : user_name, // listen on username line else Anonymous
        publish_key   : 'your_pub_key',
        subscribe_key : 'your_sub_key',
        datachannels  : true,  // Enable Data Channels
    }); 
    phone.ready(function(){ form.username.style.background="#55ff5b"; form.login_submit.hidden="true"; });
    phone.receive(function(session){
        session.connected(function(session) { video_hold.hidden=false; video_out.appendChild(session.video); });
        session.ended(function(session) { video_out.innerHTML=''; });
    });
    ... // Prepare Data Channel
    return false;
}

You can see we use the username as the phone's number, and instantiate PubNub using your own publish and subscribe keys. The next function phone.ready allows you to define a callback for when the phone is ready to place a call. I simply change the username input's background to green, but you can tailor this to your needs.

您可以看到我们使用用户名作为电话号码,并使用您自己的发布和订阅密钥实例化PubNub。 下一个功能phone.ready允许您定义何时准备好拨打电话的回调。 我只是将用户名输入的背景更改为绿色,但是您可以根据需要进行调整。

The phone.receive function allows you to define a callback that takes a session for when a session (call) event occurs, whether that be a new call, a call hangup, or for losing service, you attach those event handlers to the sessions in phone.receive.

phone.receive函数允许您定义一个回调,该回调用于在发生会话(呼叫)事件时进行会话,无论是新呼叫,呼叫挂断还是丢失服务,您都可以将这些事件处理程序附加到会话中phone.receive

I defined session.connected which is called after receiving a call when you are ready to begin talking. I simply appended the session's video element to our video div.

我定义了session.connected ,当您准备开始讲话时,会在接到电话后调用该会话。 我只是将会话的视频元素附加到我们的视频div中。

Then, I define session.ended which is called after invoking phone.hangup. This is where you place end-call logic. I simply clear the video holder's innerHTML.

然后,我定义session.ended ,它在调用phone.hangup之后被调用。 在这里放置结束呼叫逻辑。 我只是简单地清除了视频持有者的innerHTML。

We now have a phone ready to receive a call, so it is time to create a makeCall function.

现在我们已经准备好接听电话,因此现在该创建makeCall函数了。

function makeCall(form){
    if (!window.phone) alert("Login First!");
    else phone.dial(form.number.value);
    return false;
}

If window.phone is undefined, we cannot place a call. This will happen if the user did not log in first. If it is, we use the phone.dial function which takes a number and an optional list of servers to place a call.

如果未定义window.phone ,则无法拨打电话。 如果用户没有先登录,就会发生这种情况。 如果是这样,我们将使用phone.dial函数,该函数需要一个号码和一个可选的服务器列表来发出呼叫。

Finally, to end a call or hangup, simply call the phone.hangup function and hide the video div.

最后,要结束通话或挂断,只需调用phone.hangup函数并隐藏视频div。

function end(){
    if (!window.phone) return;
    window.phone.hangup();
    video_hold.hidden = true;
}

videochat

You should now have a working video chatting application! When you are ready we can move on and implement the game functions.

您现在应该有一个可以正常工作的视频聊天应用程序! 当您准备就绪时,我们可以继续并实现游戏功能。

第2部分:实施游戏 (Part 2: Implementing Your Game)

As I said earlier, the TicTacToe script has a few helpful functions. We will be using onSquareClicked, and markBox.

正如我之前所说,TicTacToe脚本具有一些有用的功能。 我们将使用onSquareClickedmarkBox

步骤1:设定游戏板 (Step 1: Setup the Game Board)

To get started, lets set a few global variables:

首先,让我们设置一些全局变量:

var game_board = document.getElementById("tic-tac-box");
var user_name = "";

The game_board will be populated with the TicTacToe board, and user_name will store the currently logged in user. We can fill our game_board with our game with the following code:

将用TicTacToe game_board填充game_board ,并且user_name将存储当前登录的用户。 我们可以使用以下代码将我们的game_board填充到我们的游戏中:

var game_board = ticTacToe(game_board);

If all goes well you should see your basic HTML backbone alongside a clickable TicTacToe board!

如果一切顺利,您应该会在可点击的TicTacToe面板旁边看到基本HTML主干!

HtmlAndBoard

步骤2:使用DataChannel API (Step 2: Using The DataChannel API)

The game_board.onSquareClicked function allows us to define a callback that will be used whenever a user makes a valid move.

game_board.onSquareClicked函数允许我们定义一个回调,该回调将在用户进行有效移动时使用。

game_board.onSquareClicked(
    function(squareNum){  // Number of the box that was clicked
        if (!window.phone) return;
        var data = {square:squareNum, username:user_name};
        window.phone.sendData(data);
    }
)

If you have followed any of my other WebRTC tutorials, you will notice that we use phone.sendData instead of phone.send here. sendData will send 1:1 messages through the WebRTC DataChannel API for immediate interactions, while send uses the 1:many PubNub streaming network. The PubNub WebRTC SDK allows us to seamlessly transition between both.

如果您已遵循我的其他任何WebRTC教程,则将注意到我们在这里使用phone.sendData而不是phone.sendsendData将通过WebRTC DataChannel API发送1:1消息以进行即时交互,而send使用1:many PubNub流网络。 PubNub WebRTC SDK允许我们在两者之间无缝过渡。

In terms of gaming, The PubNub streaming network is ideal for things like global map chat, while DataChannels are quicker for player interactions such as dodging.

在游戏方面,PubNub流媒体网络非常适合诸如全球地图聊天之类的活动,而DataChannel则可以更快地进行玩家互动(例如躲避)。

步骤3:接收邮件 (Step 3: Receiving Messages)

We have now sent messages through the DataChannel API, but we still need to implement the receiving code. The PubNub WebRTC SDK allows you to define a DataChannel callback phone.datachannel(callbackFxn) to handle incoming messages. The callback function should take one parameter, msg, which is the incoming data message.

现在,我们已经通过DataChannel API发送了消息,但是我们仍然需要实现接收代码。 PubNub WebRTC SDK允许您定义一个DataChannel回调phone.datachannel(callbackFxn)来处理传入消息。 回调函数应采用一个参数msg ,它是传入的数据消息。

function onDataReceived(msg){
    var sqr_num = msg.square;
    game_board.markBox(sqr_num);
}

Simply put, we receive the data sent in onSquareClicked, of the form {square : squareNum}, and then mark the game_board. The final step is to register this callback with our phone object. In the login function, right before we return, add a call to phone.datachannel.

简而言之,我们接收以onSquareClicked形式发送的数据,格式为{square : squareNum} ,然后标记game_board 。 最后一步是使用我们的phone对象注册此回调。 在login功能中,就在我们返回之前,将一个呼叫添加到phone.datachannel

function login(form) {
    // Setup phone
    // Ready and Receive Callbacks
    ...
    phone.datachannel(onDataReceived);
    return false;
}

Our callback has now been registered. Thats it, this will mark the box that the other player selected, allowing us to play together!

我们的回调现已注册。 就是这样,这将标记其他玩家选择的盒子,让我们一起玩!

想了解更多? (Want to learn more?)

Me too. Here are some other resources PubNub offers on WebRTC:

我也是。 以下是PubNub在WebRTC上提供的其他一些资源:

苏格兰赠品第三天 (Scotchmas Giveaway Day 3)

a Rafflecopter giveaway

Rafflecopter赠品

翻译自: https://scotch.io/tutorials/learn-webrtc-build-a-real-time-tic-tac-toe

webrtc:call

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值