03.12.2015 Views

laravel4cookbook

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Real Time Chat 188<br />

1 try {<br />

2 if (!WebSocket) {<br />

3 console.log("no websocket support");<br />

4 } else {<br />

5 var socket = new WebSocket("ws://127.0.0.1:7778/");<br />

6<br />

7 socket.addEventListener("open", function (e) {<br />

8 console.log("open: ", e);<br />

9 });<br />

10<br />

11 socket.addEventListener("error", function (e) {<br />

12 console.log("error: ", e);<br />

13 });<br />

14<br />

15 socket.addEventListener("message", function (e) {<br />

16 console.log("message: ", JSON.parse(e.data));<br />

17 });<br />

18<br />

19 console.log("socket:", socket);<br />

20<br />

21 window.socket = socket;<br />

22 }<br />

23 } catch (e) {<br />

24 console.log("exception: " + e);<br />

25 }<br />

.<br />

This was extracted from public/js/shared.js.<br />

We’ve wrapped this code in a try-catch block as not all browsers support Web Sockets yet. There<br />

are a number of libraries which will shim this functionality, but their use is outside the scope of this<br />

tutorial.<br />

You can find a couple of these libraries at: https://github.com/gimite/web-socket-js and https://github.com/sockjs.<br />

.<br />

This code will attempt to open a socket connection to 127.0.0.1:7778 (the address and port used in<br />

the serve command) and write some console messages depending on the events that are emitted.<br />

You’ll notice we’re also assigning the socket instance to the window object; so we can send some

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!