When I run the node server, the console indicates "info - socket.io started". However, it never detects a connection from the client side. I believe it is an issue with the installation of socket.io as I am running a Windows 7 machine...
When I attempt to connect to the server from the client side my server console indicates "debug - served static content /lib/socket.io.js".
Anyone have any suggestions how I can get socket io to succesfully connect from the client side on my Windows 7 machine?
Right now, I have the socket.io folder located in the following directory:
nodejs/node_modules/socket.io/
I have the following code on the server side for a tcp server in node:
var http = require('http'),
sys = require('util'),
fs = require('fs'),
io = require('socket.io');
console.log('Creating server...');
var server = http.createServer(function(request, response) {
response.writeHead(200, {
'Content-Type': 'text/html'
});
var rs = fs.createReadStream(__dirname + '/template.html');
sys.pump(rs, response);
});
var socket = io.listen(server);
socket.on('connection', function(client) {
var username;
console.log('New client connected.');
client.send('Welcome to this socket.io chat server!');
client.send('Please input your username: ');
client.on('message', function(message) {
if (!username) {
username = message;
client.send('Welcome, ' + username + '!');
return;
}
socket.broadcast(username + ' sent: ' + message);
});
});
server.listen(20000);
This is the code on the client side:
<!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 type="text/javascript" src="http://localhost:20000/socket.io/lib/socket.io.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var entry_el = $('#entry');
var socket = new io.Socket('localhost', {port: 20000});
socket.connect();
console.log('connecting...');
socket.on('connect', function() {
console.log('connect');
});
socket.on('message', function(message) {
var data = message.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">");
$('#log ul').append('<li>' + data + '</li>');
window.scrollBy(0, 1000000000000000);
entry_el.focus();
});
entry_el.keypress(function(event) {
if (event.keyCode != 13) return;
var msg = entry_el.attr('value');
if (msg) {
socket.send(msg);
entry_el.attr('value', '');
}
});
});
</script>
<style type="text/css">
body {
background-color: #666;
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 {
background-color: black;
color: white;
border-top:1px solid white;
position: fixed;
bottom: 0;
width: 100%;
font-size: 18px;
}
#console input {
width: 100%;
background-color: inherit;
color: inherit;
font-size: inherit;
}
</style>
</head>
<body>
<h1>Chat</h1>
<div id="log"><ul></ul></div>
<div id="console">
<input type="text" id="entry" />
</div>
</body>
</html>
Thanks!
Your socketio js should be inside the following path
http://{host:port}/socket.io/socket.io.js
In your case you need to include as follows
<script type="text/javascript" src="http://localhost:20000/socket.io/lib/socket.io.js"></script>
Related
I'm trying to run a login project within nmp, I initialized the project, then the db side.
For now, when I try to run index.html and I get the mentioned above error. As well I'm not sure how to configure the "Run Configuration" of the project. Is anything wrong in my code? And where can I find more information on how to configure "Run Configuration" of the project accordingly.
var mysql = require('mysql');
var express = require('express');
var session = require('express-session');
var bodyParser = require('body-parser');
var path = require('path');
var connection = mysql.createConnection({
host : 'Host',
user : 'root',
password : '',
database : 'nodeDB'
});
var app = express();
app.use(session({
secret: 'secret',
resave: true,
saveUninitialized: true
}));
app.use(bodyParser.urlencoded({extended : true}));
app.use(bodyParser.json());
app.get('/', function(request, response) {
response.sendFile(path.join(__dirname + '/index.html'));
});
app.post('/auth', function(request, response) {
var username = request.body.username;
var password = request.body.password;
if (username && password) {
connection.query('SELECT * FROM account WHERE username = ? AND password = ?', [username, password], function(error, results, fields) {
if (results.length > 0) {
request.session.loggedin = true;
request.session.username = username;
response.redirect('/home');
} else {
response.send('Incorrect Username and/or Password!');
}
response.end();
});
} else {
response.send('Please enter Username and Password!');
response.end();
}
});
app.get('/home', function(request, response) {
if (request.session.loggedin) {
response.send('Welcome back, ' + request.session.username + '!');
} else {
response.send('Please login to view this page!');
}
response.end();
});
app.listen(3000);
<script src="/index.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Login Form Tutorial</title>
<style>
.login-form {
width: 300px;
margin: 0 auto;
font-family: Tahoma, Geneva, sans-serif;
}
.login-form h1 {
text-align: center;
color: #4d4d4d;
font-size: 24px;
padding: 20px 0 20px 0;
}
.login-form input[type="password"],
.login-form input[type="text"] {
width: 100%;
padding: 15px;
border: 1px solid #dddddd;
margin-bottom: 15px;
box-sizing:border-box;
}
.login-form input[type="submit"] {
width: 100%;
padding: 15px;
background-color: #535b63;
border: 0;
box-sizing: border-box;
cursor: pointer;
font-weight: bold;
color: #ffffff;
}
</style>
</head>
<body>
<div class="login-form">
<h1>Login Form</h1>
<form action="auth" method="POST">
<input type="text" name="username" placeholder="Username" required>
<input type="password" name="password" placeholder="Password" required>
<input type="submit">
</form>
</div>
</body>
</html>
you are missing script 'start' in package.json file.
If you add below code to your file it should run fine.
"scripts":{
"start": "node app"
}
where app is your file name in which server is starting.
i have a javascript code that setup a websocket connection and have several functions.
The websocket works fine.
but i want to run a javascript function from the script inside the html code.this does not work. if i run the function from a onclick event, then it works fine (see the button).
i have tried the body onload but it does not work.
My goal is: execute the function OnloadFunction if the webpage is loaded. Then it should send a string with websocket.
<!DOCTYPE html><html>
<head>
<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">
<link rel=\"icon\" href=\"data:,\">
<title>Testpage</title>
<meta charset="UTF-8">
<style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center; background-color:#5593F1}
.button { background-color: #195B6A; border: none; color: white; padding: 10px 40px;
text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}
.button2 {background-color: #77878A;}
</style>
<script>
var connection;
connection = new WebSocket('ws://' + window.location.hostname + ':81/');
connection.onopen = function () { connection.send('Connect ' + new Date()); };
connection.onerror = function (error) { console.log('WebSocket Error ', error);};
connection.onmessage = function (e) { console.log('Server: ', e.data);};
function OnloadFunction() {
connection.send('* Test22');
alert("Hello! ");
}
</script>
</head>
<body onload="javascript:OnloadFunction();">
<h1>Testpage</h1>
<p>Suche....</p>
<p><button class="button" onclick="OnloadFunction()">read</button></p>
</body>
</html>
This is a simple test from me but does not work also
<body>
<h1>Test</h1>
<p>Suche...</p>
<p><button class="button" onclick="OnloadFunction()">Lesen</button></p>
<script>
var connection = new WebSocket('ws://' + window.location.hostname + ':81/');
connection.onopen = function () { connection.send('Connect ' + new Date()); };
connection.onerror = function (error) { console.log('WebSocket Error ', error);};
connection.onmessage = function (e) { console.log('Server: ', e.data);};
connection.send('* Test22');
</script>
</body>
What is wrong? How can i execute the function OnloadFunction() in the html code if the webside is loaded?
EDIT1:
Thank you for all the suggestions. i have tried much different ways but nothing works.
Now I am close to a solution but I do not understand the new error.
The function start() is executet because of window.onload=start;
But the code after connection.onmessage = function(evt) { console.log(evt);};
is only executet if the alert("TEST___"); is in the code. if i delete this line then the code after that is not executet. Why is the code not executet without alert("TEST___"); ?? With the button onclick all works well without the alert.
Here my code websock2.js (the alters are only for testing):
var connection;
function OnloadFunction() {
connection.send('* Test22'+' x');
alert("LOADED! ");
}
function start() {
alert("Start! ");
connection = new WebSocket('ws://' + window.location.hostname + ':81/');
<!-- connection = new WebSocket('ws://192.168.1.5:81/',['arduino']); -->
connection.onopen = function () { connection.send('Connect ' + new Date()); };
connection.onerror = function (error) { console.log('WebSocket Error ', error);};
connection.onmessage = function(evt) { console.log(evt);};
alert("TEST___");
connection.send('* Test22'+' x');
console.log('effekt: ');
alert("LOADED! ");
}
window.onload=start;
Here my html code:
<!DOCTYPE html><html>
<head>
<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">
<link rel=\"icon\" href=\"data:,\">
<title>Testpage</title>
<meta charset="UTF-8">
<script src="websock2.js" async></script>
<style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center; background-color:#5593F1}
.button { background-color: #195B6A; border: none; color: white; padding: 10px 40px;
text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}
.button2 {background-color: #77878A;}
</style>
</head>
<body>
<h1>Testpage</h1>
<p>read....</p>
<p><button class="button" onclick="OnloadFunction()">Lesen</button></p>
</html>
I have this simple chat room here:
app.js
const app = require('express')();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const fs = require('fs');
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket) {
var messages;
fs.readFile('log.txt', 'utf8', function(err, data) {
messages = data.split('|/');
for (i = 0; i < messages.length; i++) {
socket.emit('message', messages[i]);
}
if (err) throw err;
})
socket.on('message', function(data) {
fs.appendFile('log.txt',
'<span class="seen">' + data.name + ': ' + data.msg + '</span>' + '|/',
function(err) {
if (err) throw err;
})
socket.broadcast.emit('message', data);
})
})
http.listen(2099, function(){
console.log('litening on :2099');
});
index.HTML
<!DOCTYPE html>
<meta charset="UTF-8">
<html>
<head>
<title>chat</title>
<style>
body {
font-family: sans-serif;
font-size: 18px;
background: #404040;
}
input[type=text],[type=submit] {
font-size: 18px;
}
#chatList {
list-style: none;
margin: 0;
padding: 0;
}
#inputContainer {
position: fixed;
bottom: 0;
width: 100%;
margin: 10px;
}
#input {
width: calc(90% - 40px);
padding: 10px 20px;
border: 1px solid white;
border-radius: 10px;
margin-right: -3px;
display: inline-block;
color: white;
background: #404040;
}
#submit {
border: 1px white solid;
border-radius: 10px;
padding: 11px 2.2%;
color: white;
background-color: #404040;
}
.msg {
margin: 0 12px 0px 12px;
padding: 12px;
border-bottom: 1px solid gray;
color: white;
}
.income {
color: crimson;
}
.sender {
color: cyan;
}
</style>
</head>
</head>
<body>
<div id='chat'>
<ul id='chatList'>
</ul>
</div>
<div id='inputContainer'>
<input type="text" id='input' placeholder="Type a message..." autocomplete="off">
<input type="submit" id='submit' value="Send" onclick="send()">
</div>
</form>
<script src='/socket.io/socket.io.js'></script>
<script>
document.getElementById('input').value = '';
var socket = io();
document.addEventListener("keydown", function(e) {
if (e.keyCode == 13) {
send();
}
})
function send() {
value = document.getElementById('input').value;
if (value != '') {
socket.emit('message', {msg: value, name: username})
var list = document.getElementById('chatList');
var msg = document.createElement('li');
msg.className = 'msg';
msg.innerHTML = '<span class="sender">' + username + '</span>' + ': ' + value;
list.appendChild(msg);
document.getElementById('input').value = '';
}
}
socket.on('message', function(data) {
var list = document.getElementById('chatList');
var msg = document.createElement('li');
msg.className = 'msg';
msg.innerHTML = data;
list.appendChild(msg);
})
document.getElementById('input').value = '';
var username = prompt('Choose a username:');
if (username == '') {
username = 'mysteryman' + Math.floor(Math.random() * 100);
}
</script>
</body>
</html>
So this function:
fs.readFile('log.txt', 'utf8', function(err, data) {
messages = data.split('|/');
for (i = 0; i < messages.length; i++) {
socket.emit('messages', messages[i]);
}
if (err) throw err;
})
Were suppose to read data from log.txt and send it as events for the clients to load in old messages. Its working okay but the client side is not receiving any events even though this loop is running and sending events.
I have tried making sure that all events are loaded before sending the data.
Any help would be greatly appreciated!!!
Your typo mistake, you emit messages event on server side, but listen to message (without s) event on client side.
My guess is when the server fires the socket.emit('message'..., the socket in the client has not been registered yet the socket.on('message'...
I am trying to write a web chat client in socket.io, but first I need to get my server talking to the website on localhost.
I am getting the 'listening' message, but nothing happens when I open up localhost in a new tab to say that a user connected. Apache server is running, so is express, so is node.js.
Here is my index.js, which serves up my index.html:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');});
io.on('connection', function(socket){
console.log('a user connected');});
http.listen(3000, function(){
console.log('listening on *:3000');});
and here is my index.html:
<!DOCTYPE html PUBLIC>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css" />
<title>Web chat practice</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>
Here will be the web chat:
<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>
</body>
</html>
I could also use some general direction in the MEAN stack.
This line of code in index.html creates an error:
var socket = io.();
The code should be:
var socket = io();
This will connect to your Express server/socket.io (if the web page is being served by that Express server). That should generate the 'a user connected' message in your server console, but it won't do anything else because your web page doesn't do anything else with socket.io.
In addition, your server code looks suspect. I'd suggest you take the Express 4 example right from here: http://socket.io/docs/#using-with-the-express-framework.
I do not understand why you mention an Apache server as that is not typically part of an Express/socket.io implementation.
I have followed a tutorial for socket.io chat:
https://www.youtube.com/watch?v=pNKNYLv2BpQ
In the tutorial video it works fine however mine does not work at all. The messages do not seem to be sent or received by either the server or the client
This is my app.js run on the server side with node
var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server);
server.listen(3000);
app.get('/', function(req, res) {
res.sendfile(__dirname + '/index.html');
});
io.sockets.on('connection', function(socket) {
socket.on('send message', function(data) {
io.sockets.emit('new message', data);
});
});
This is my index.html client
<html>
<head>
<title>Chat with socket.io and node.js</title>
<style>
#chat
{
height: 500px;
}
</style>
</head>
<body>
<div id="chat"></div>
<form id="send-message">
<input size="35" id="message"></input>
<input type="submit"></input>
</form>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
jQuery(function($) {
var socket = io.connect();
var $messageForm = $('#send-message');
var $messageBox = $('#message');
var $chat $('#chat');
$messageForm.submit(function(e) {
e.preventDefault();
socket.emit('send message', $messageBox.val());
$messageBox.val('');
});
socket.on('new message', function(data) {
$chat.append(data + "<br/>");
});
});
</script>
I suppose it is a simple error that I have overlooked but I'm stumped at the moment, any ideas ??? Also if you require additional information please say so :)
create one index.html file
index.html
<!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>
</body>
</html>
<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>
index.js
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('connection', function(socket){
console.log('a user connected');
socket.on('chat message', function(msg){
console.log('message: ' + msg);
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
For more information click here