I have a few questions regarding using an IO socket with PHP, etc. I am new to nodejs / socket io, so I know very little, I just started using it in the last few days, and I get to the point where I will implement this on my website (at the moment I just had small examples tests).
Question: Currently, I have to add a port to my local host in order to view it and make it work, it is obvious that I cannot have this when it is a live website, and I also can not do this when I use php pages (just doing examples with html) If I use port 4000 for my io server socket, I have to go to: localhost: 4000, however I need to be able to go to: localhost: 8888 / mysitefolder (8888 port for my MAMP, for php and all) I saw in questions where people solved this, but I could not get it to work for myself.
Here is my code:
chat.js
var app = require('express').createServer(),
io = require('socket.io').listen(app);
app.listen(4000);
var users = [];
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
io.sockets.on('connection', function (socket) {
socket.emit('connected');
socket.on('userID', function (userID) {
users.push(userID);
});
socket.on('message', function (message) {
socket.broadcast.emit('message-response', { data: message});
});
});
index.html
<title>Testing</title>
<script src="/socket.io/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
function mktime(){
var newDate = new Date;
return newDate.getTime();
}
function appendMessage(data)
{
$("body").append(data+"<br />");
}
var socket = io.connect('http://localhost:4000');
socket.on('connected', function () {
socket.emit("userID", mktime());
});
socket.on('message-response', function (message) {
appendMessage(message.data);
});
$(document).ready(function(){
$('#input').keypress(function(event) {
if (event.keyCode != 13) return;
var msg = $("#input").val();
if (msg) {
socket.emit('message', msg );
appendMessage(msg);
$("#input").val('').focus();
}
});
});
</script>
<body>
<input type="text" id="input"><br>
</body>
source
share