Unity3D Webplayer extension on pure Node.js server - node.js

I can't run my Unity3D applications on my node.js server. It says "failed to download data file". I think it's because of MIME types. Here are my codes. I'm new to Javascript and Node.js, sorry for that.
Server.js:
var http = require("http");
var url = require('url');
var fs = require('fs');
var io = require('socket.io');
var five = require("johnny-five"),board, led, button;
board = new five.Board();
board.on("ready", function() {
button = new five.Button(2);
});
var server = http.createServer(function(request, response){
console.log('Connection');
var path = url.parse(request.url).pathname;
switch(path){
case '/':
response.writeHead(200, {'Content-Type': 'text/html'});
response.write('hello world', function(err) { response.end(); });
break;
case '/index.html':
fs.readFile(__dirname + path, function(error, data){
if (error){
response.writeHead(404);
response.write("opps this doesn't exist - 404");
}
else{
response.writeHead(200, {"Content-Type": "text/html"});
response.write(data, function(err) { response.end(); });
}
});
break;
default:
response.writeHead(404);
response.write("opps this doesn't exist - 404", function(err) { response.end(); });
break;
}
});
server.listen(8001);
var ios = io.listen(server);
ios.listen(server);
ios.sockets.on('connection', function (socket) {
if (board.isReady) {
button.on("down",function(){
console.log("down");
socket.emit('news', { hello: 'world' });
});
socket.on('toggleLed', function(data){
led = new five.Led(13);
led.strobe(1000);
});
setInterval(function(){
socket.emit('date', {'date': new Date()});
});
socket.on('client_data', function(data){
process.stdout.write(data.letter);
});
}
});
Index.html:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Unity Web Player | UnityArduino</title>
<script type='text/javascript' src='https://ssl-webplayer.unity3d.com/download_webplayer-3.x/3.0/uo/jquery.min.js'></script>
<script type="text/javascript">
<!--
var unityObjectUrl = "http://webplayer.unity3d.com/download_webplayer-3.x/3.0/uo/UnityObject2.js";
if (document.location.protocol == 'https:')
unityObjectUrl = unityObjectUrl.replace("http://", "https://ssl-");
document.write('<script type="text\/javascript" src="' + unityObjectUrl + '"><\/script>');
-->
</script>
<script type="text/javascript">
<!--
var config = {
width: 960,
height: 600,
params: { enableDebugging:"0" }
};
var u = new UnityObject2(config);
jQuery(function() {
var $missingScreen = jQuery("#unityPlayer").find(".missing");
var $brokenScreen = jQuery("#unityPlayer").find(".broken");
$missingScreen.hide();
$brokenScreen.hide();
u.observeProgress(function (progress) {
switch(progress.pluginStatus) {
case "broken":
$brokenScreen.find("a").click(function (e) {
e.stopPropagation();
e.preventDefault();
u.installPlugin();
return false;
});
$brokenScreen.show();
break;
case "missing":
$missingScreen.find("a").click(function (e) {
e.stopPropagation();
e.preventDefault();
u.installPlugin();
return false;
});
$missingScreen.show();
break;
case "installed":
$missingScreen.remove();
break;
case "first":
break;
}
});
u.initPlugin(jQuery("#unityPlayer")[0], "ArduinoWebPlayer.unity3d");
});
-->
</script>
<style type="text/css">
<!--
body {
font-family: Helvetica, Verdana, Arial, sans-serif;
background-color: white;
color: black;
text-align: center;
}
a:link, a:visited {
color: #000;
}
a:active, a:hover {
color: #666;
}
p.header {
font-size: small;
}
p.header span {
font-weight: bold;
}
p.footer {
font-size: x-small;
}
div.content {
margin: auto;
width: 960px;
}
div.broken,
div.missing {
margin: auto;
position: relative;
top: 50%;
width: 193px;
}
div.broken a,
div.missing a {
height: 63px;
position: relative;
top: -31px;
}
div.broken img,
div.missing img {
border-width: 0px;
}
div.broken {
display: none;
}
div#unityPlayer {
cursor: default;
height: 600px;
width: 960px;
}
-->
</style>
</head>
<body>
<p class="header"><span>Unity Web Player | </span>UnityArduino</p>
<div class="content">
<div id="unityPlayer">
<div class="missing">
<a href="http://unity3d.com/webplayer/" title="Unity Web Player. Install now!">
<img alt="Unity Web Player. Install now!" src="http://webplayer.unity3d.com/installation/getunity.png" width="193" height="63" />
</a>
</div>
<div class="broken">
<a href="http://unity3d.com/webplayer/" title="Unity Web Player. Install now! Restart your browser after install.">
<img alt="Unity Web Player. Install now! Restart your browser after install." src="http://webplayer.unity3d.com/installation/getunityrestart.png" width="193" height="63" />
</a>
</div>
</div>
</div>
<p class="footer">« created with Unity »</p>
</body>
</html>
Thank you for your help.

I found that it is because of this server code.
var server = http.createServer(function(request, response){
console.log('Connection');
var path = url.parse(request.url).pathname;
switch(path){
case '/':
response.writeHead(200, {'Content-Type': 'text/html'});
response.write('hello world', function(err) { response.end(); });
break;
case '/index.html':
fs.readFile(__dirname + path, function(error, data){
if (error){
response.writeHead(404);
response.write("opps this doesn't exist - 404");
}
else{
response.writeHead(200, {"Content-Type": "text/html"});
response.write(data, function(err) { response.end(); });
}
});
break;
default:
response.writeHead(404);
response.write("opps this doesn't exist - 404", function(err) { response.end(); });
break;
}
});
I followed this code and found the solution.
https://github.com/jwanga/node-static-http-server

Related

Dynamic rooms in Socket.io

I'm new in node.js and socket.io. I didn't understand how to work with rooms. I'm creating something like a Private Messages. Each pair of users have their unique room.
From documentation:
io.on('connection', function(socket){
socket.join('some room');
});
But I need to create a room from client side. Because it's dynamic. How?
I met some examples https://gist.github.com/crtr0/2896891
server.js
io = socketio.listen(server);
io.sockets.on('connection', function(socket) {
socket.on('room', function(room) {
socket.join(room);
});
});
room = "abc123";
io.sockets.in(room).emit('message', 'what is going on, party people?');
This line drives me crazy. It seems to me stupid. Because server never know which room to use. Server just can handle multiple rooms.
room = "abc123";
Please, help or explain.
In you above code you have fixed room to abc123 , that you need to make it dynamic for all connected clients . You can provide room create option to user also you can provide logic to change/rename/leave/join room from client. Basically in your client and server you can apply below logical changes.
Client logic to update or change room :
socket.emit('switchRoom', newRoom);
socket.on('updaterooms', function(rooms, current_room) {
// Update new room logic
}
Server Logic to handle room change :
socket.on('switchRoom', function(newroom){
// leave the current room (stored in session)
socket.leave(socket.room);
// join new room, received as function parameter
socket.join(newroom);
socket.emit('updatechat', 'SERVER', 'you have connected to '+ newroom);
// sent message to OLD room
socket.broadcast.to(socket.room).emit('updatechat', 'SERVER', socket.username+' has left this room');
// update socket session room title
socket.room = newroom;
socket.broadcast.to(newroom).emit('updatechat', 'SERVER', socket.username+' has joined this room');
socket.emit('updaterooms', rooms, newroom);
});
Refer Below Example :
Socket.io Multi-room Example
Rooms and Namespace in socket.io
Okay, I solved my problem! If you use rooms within namespaces, don't forget write .of('your_namespace')
I created my own way of creating rooms from client side dynamically and it worked.
You can found video tutorial on youtube. https://www.youtube.com/watch?v=q5OKKudZTeY&list=PLZdwvOOinjFbzhZutEK9HvC56nicFXSpZ&index=8&t=0s
I used EJS for rendering.
Index.js
const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);
const path = require('path');
const roomsList = [];
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.get('/', (req, res) => {
//res.sendFile(__dirname + '/index.html');
res.render(path.join(__dirname,'/','index.html'),{rooms: roomsList});
});
app.get('/room/', (req, res) => {
var name = req.query.name;
res.render(path.join(__dirname,'/','rooms.html'),{rooms: name});
});
app.get('/addRoom/', (req, res) => {
var name = req.query.name;
roomsList.push(name);
console.log(JSON.stringify(roomList));
res.send(200);
});
const adminNameSpace = io.of('/admin');
adminNameSpace.on('connect', (socket) => {
//console.log('a user connected');
socket.on('join', (data)=>{
socket.join(data.room);
adminNameSpace.in(data.room).emit('chat message', `New Person joined the ${data.room} room `);
});
socket.on('disconnect', () => {
console.log('user disconnected');
});
socket.on('chat message', (data) => {
console.log('message: ' + data.msg);
adminNameSpace.in(data.room).emit('chat message', data.msg);
});
socket.on('send msg to all', (data) => {
console.log('message: ' + data.msg);
adminNameSpace.emit('chat message', data.msg);
});
});
server.listen(3000, () => {
console.log('listening on *:3000');
});
index.html
<html>
<head>
</head>
<body>
<p>Select your room!</p>
<p>Create Rooms</p>
<input id='input-room-name' />
<button onclick="createRoom()">Create Room</button><br/>
<script>
const rooms = '<%= rooms %>';
const roomList = rooms.split(',');
function createRoom()
{
var name = document.getElementById('input-room-name').value;
document.body.innerHTML+= `${name}<br /><br />`;
httpGet(name);
}
function httpGet(name)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", `/addRoom?name=${name}`,false);
xmlHttp.send(null);
return xmlHttp.responseText;
}
for (const name of roomList)
{
if(name!='')
document.body.innerHTML += `${name}<br /><br />`;
}
</script>
</body>
</html>
rooms.html
<!DOCTYPE html>
<html>
<head>
<title>Socket.IO chat</title>
<style>
body { margin: 0; padding-bottom: 3rem; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; }
#form { background: rgba(0, 0, 0, 0.15); padding: 0.25rem; position: fixed; bottom: 0; left: 0; right: 0; display: flex; height: 3rem; box-sizing: border-box; backdrop-filter: blur(10px); }
#input { border: none; padding: 0 1rem; flex-grow: 1; border-radius: 2rem; margin: 0.25rem; }
#input:focus { outline: none; }
#form > button { background: #333; border: none; padding: 0 1rem; margin: 0.25rem; border-radius: 3px; outline: none; color: #fff; }
#messages { list-style-type: none; margin: 0; padding: 0; }
#messages > li { padding: 0.5rem 1rem; }
#messages > li:nth-child(odd) { background: #efefef; }
</style>
</head>
<body>
<h1><%= rooms %></h1>
<button onclick="sendMSGToAll()">Send Message to all</button>
<ul id="messages"></ul>
<form id="form" action="">
<input id="input" autocomplete="off" /><button>Send</button>
</form>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io('/admin');
var form = document.getElementById('form');
var input = document.getElementById('input');
const room = '<%= rooms %>';
form.addEventListener('submit', function(e) {
e.preventDefault();
if (input.value) {
socket.emit('chat message', {msg: input.value, room});
input.value = '';
}
});
socket.on('chat message', function(msg) {
var item = document.createElement('li');
item.textContent = msg;
messages.appendChild(item);
window.scrollTo(0, document.body.scrollHeight);
});
socket.on('connect', () => {
socket.emit('join', {room: room});
})
function sendMSGToAll()
{
socket.emit('send msg to all', {msg: input.value, room});
}
</script>
</body>
</html>

Socket.io Can somebody help me why connected/disconnected message is appearing twice?

Below is my server side code where I want to display if user is connected or disconnected.But the user is connected and user is disconnected message is appearing twice. Can somebody help me why is it appearing twice?
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res) {
res.sendfile('index.html');
});
io.on('connect', function(socket) {
socket.broadcast.emit('chat message', 'a user connected!');
socket.on('disconnect', function() {
socket.broadcast.emit('chat message', 'user disconnected');
});
socket.on('chat message', function(msg) {
socket.broadcast.emit('chat message', msg);
});
});
http.listen(3000, function() {
console.log('listening on *:3000');
});
Client Code
<!doctype html>
<html>
<head>
<title>Socket.IO chat</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font: 13px Helvetica, Arial; }
form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
#messages { list-style-type: none; margin: 0; padding: 0; }
#messages li { padding: 5px 10px; }
#messages li:nth-child(odd) { background: #eee; }
</style>
</head>
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
</script>
<script src="/socket.io/socket.io.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
var socket = io();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
});
</script>
<script>
var typing = false;
var timeout = undefined;
function timeoutFunction(){
typing = false;
socket.emit(noLongerTypingMessage);
}
function onKeyDownNotEnter(){
if(typing == false) {
typing = true
socket.emit(typingMessage);
timeout = setTimeout(timeoutFunction, 3000);
} else {
clearTimeout(timeout);
timeout = setTimeout(timeoutFunction, 3000);
}
}
</script>
</body>
</html>
You have two copies of this in your client file:
script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
</script>
Remove one of them.
Correct your order
io.on('connect', function(socket) {
socket.broadcast.emit('chat message', 'a user connected!');
socket.on('chat message', function(msg) {
socket.broadcast.emit('chat message', msg);
});
socket.on('disconnect', function() {
socket.broadcast.emit('chat message', 'user disconnected');
});
});

Unable to pass content from one part of extension to another

I have an issue in passing content from my background.html file to my popup.html one. Here's what I'm doing on background.js:
var pollInterval = 15000 * 60; // 15 minutes, in milliseconds
function getBandi() {
$.get('http://www.comune.cormons.go.it/index.php?id=6367&no_cache=1', function (data) {
var $data = $(data);
var $bandi = $data.find('.news-latest-container .news-latest-item').has('h3:contains("Bando")');
var itemsArray = [];
$bandi.each(function () {
itemsArray.push($(this).html());
});
chrome.runtime.sendMessage({messaggi: itemsArray}, function(response) {
console.log(response);
});
});
}
function initRequest() {
getBandi();
window.setTimeout(initRequest, pollInterval)
}
$(document).ready(function () {
initRequest();
});
here's my popup html file
<!doctype html>
<style type="text/css">
#mainPopup {
padding: 10px;
height: 200px;
width: 400px;
font-family: Helvetica, Ubuntu, Arial, sans-serif;
}
h1 {
font-size: 2em;
}
</style>
<script type="text/javascript" src="../../js/jquery/jquery.min.js"></script>
<script type="text/javascript" src="browser_action.js"></script>
<div id="mainPopup">
<h1>Bandi Disponibili a Cormons</h1>
<ul id="messaggi"></ul>
</div>
Here's my javascript for the popup:
$(document).ready(function () {
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
console.log('sono qui?')
var $container = $('#messaggi');
var $array = request.messaggi;
$array.each(function () {
$container.append("<li/>").html($(this).html());
});
sendResponse({test: true});
});
});
It is obvious by now that I'm definitely screwing something on the usage of chrome.runtime messages. But I can't figure what exactly (it is my first and probably last chrome extension).

How to connect to Socket.IO from client to server

Im developing a real-time chat web-application for my site. My server acts a little different to the way i need to act. i have an Apache PHP server which node.js is not compatible on. My node server is public but to connect, i have to name a directory of the client from the server which means that when i open up the SERVER IP, it will display the client. I want to upload the client on another Hosting server and connect to my Socket.IO and node server from there. Here is my code.
Client
<!DOCTYPE html>
<html lang='en'>
<head>
<title>Chat</title>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js'></script>
<script src='node_modules/socket.io/socket.io.js'></script>
<script>
var socket = new io.Socket("127.0.0.1", {port:911});
socket.connect();
//Once connected
socket.on('welcome', function(data) {
$('#log ul').append('<li>' + data.salutation + '</li>');
});
//Displayig the data from the server
socket.on('data from server', function(data) {
$('#log ul').append('<li>' + data.message + '</li>');
});
$(function() {
var entry_el = $('#entry');
$('#entry').keypress(function(event) {
//13 on your keyboard is the key enter
if(event.keyCode == 13) {
var msg = entry_el.attr('value');
if(msg) {
socket.emit('data from client', {'text': msg});
entry_el.attr('value', '');
window.scrollBy(0, 1000000000000);
entry_el.focus();
}
}
});
});
/*SCRIPT DONE
CSS START
*/
</script>
<style type='text/css'>
body {
color: fff;
font-size: 14px;
margin: 0;
padding: 0;
font-family: Helvetica, Arial, Sans-Serif;
}
#log {
margin-bottom: 100px;
width: 100%;
}
#log ul {
padding: 0;
margin: 0;
}
#log ul li {
list-style-type: none;
}
#console {
position: fixed;
width: 100%;
font-size: 18px;
}
</style>
</head>
<body>
<h1>Chat</h1>
<div id='log'><ul></ul></div>
<div id='console'>
<input type='text' id='entry'/>
</div>
</body>
</html>
Server
var http = require('http').createServer(handler);
var io = require('socket.io').listen(http);
var sys = require('sys');
var fs = require('fs');
var clients = [];
http.listen(911);
function handler(request, response) {
//If the response is Positive (200)
response.writeHead(200, {
'Content-Type':'text/html'
});
sys.pump(rs, response);
};
//connecting to sockets
io.sockets.on('connection', function(socket) {
var username;
clients.push(socket);
socket.emit('welcome', {'salutation':'Welcome to this chat server!'});
socket.emit('welcome', {'salutation':'Please input your username:'});
socket.on('data from client', function(data) {
console.log('message: ' + data.text);
if(!username) {
username = data.text;
socket.emit('data from server', {'message': 'Welcome, ' + username + '!'});
return;
}
//the response when someone types something
var feedback = username + ' said: ' + data.text;
clients.forEach(function(socket) {
socket.emit('data from server', {'message': feedback});
});
});
});

Dynamic rooms with Socket.io and Node

I'm trying to use the new "room" feature in Socket.io v.7 to create dynamic chat rooms, but I'm having problems getting static rooms to work in my example. Based on the URL the user selects they should end up in room1 or room2. Anything the user enters in the chat should be broadcast to users in the same room. I have 2 browsers (chrome & ff) each with a tab open to /room1 and /room2, however nothing I type in seems to be broadcast to the other tabs. What am I doing wrong?
Server code
var app = require('express').createServer();
var io = require("socket.io").listen(app);
io.sockets.on('connection', function (socket) {
// join to room and save the room name
socket.on('join room', function (room) {
socket.set('room', room, function() { console.log('room ' + room + ' saved'); } );
socket.join(room);
})
socket.on('message', function(data) {
console.log("Client data: " + data);
// lookup room and broadcast to that room
socket.get('room', function(err, room) {
//room example - https://github.com/learnboost/socket.io
// neither method works for me
socket.broadcast.to(room).emit('new fan');
io.sockets.in(room).emit('new non-fan');
})
})
});
app.get('/room1', function(req, res){
res.render('example2-client.ejs', {layout:false});
});
app.get('/room2', function(req, res){
res.render('example2-client-2.ejs', {layout:false});
});
app.listen(4000);
Client code room 1
<!DOCTYPE HTML>
<html><head>
<title>Code review for Snipet</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript" src="http://localhost:4000/socket.io/socket.io.js"></script>
<script>
$(document).ready(function() {
var socket = io.connect('http://localhost:4000');
$("#msgbox").keypress( function(event) {
if (event.which == '13') {
sendmsg();
event.preventDefault();
}
});
socket.on('connect', function (data) {
socket.emit('join room', 'room1' );
});
socket.on('message', function (data) {
add_message(data);
});
function add_message(m) {
$("#chatlog").append(m);
$("#chatlog").append("<BR>");
}
function sendmsg()
{
var r = $("#msgbox").val();
socket.emit('message', r );
add_message(r);
$("#msgbox").val('');
}
});
</script>
</head>
<body>
<div id="chat" style="height: 200px; width: 200px; border: 1px solid grey;">
<div id="chatlog" style="height: 178px; width: 200px; overflow-y: scroll;"></div>
<input type="text" id="msgbox" style="margin-left: 2px; width: 193px;">
</div>
</body>
</html>
Client code 2
<!DOCTYPE HTML>
<html><head>
<title>Code review for Snipet</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript" src="http://localhost:4000/socket.io/socket.io.js"></script>
<script>
$(document).ready(function() {
var socket = io.connect('http://localhost:4000');
$("#msgbox").keypress( function(event) {
if (event.which == '13') {
sendmsg();
event.preventDefault();
}
});
socket.on('connect', function (data) {
socket.emit('join room', 'room2' );
});
socket.on('message', function (data) {
add_message(data);
});
function add_message(m) {
$("#chatlog").append(m);
$("#chatlog").append("<BR>");
}
function sendmsg()
{
var r = $("#msgbox").val();
socket.emit('message', r );
add_message(r);
$("#msgbox").val('');
}
});
</script>
</head>
<body>
<div id="chat" style="height: 200px; width: 200px; border: 1px solid grey;">
<div id="chatlog" style="height: 178px; width: 200px; overflow-y: scroll;"></div>
<input type="text" id="msgbox" style="margin-left: 2px; width: 193px;">
</div>
</body>
</html>
You don't seem to be listening to these events
socket.broadcast.to(room).emit('new fan');
io.sockets.in(room).emit('new non-fan');
on the client side you need:
socket.on('new fan', function (data) {
console.log('new fan');
});
You're also not sending the message to the clients.
Inside:
socket.on('message', function(data) { })
on the server, you need to do :
io.sockets.in(room).emit('message', data);

Resources