app.js
app.get('/',function(req,res){
res.sendfile(__dirname + '/index.html');
console.log('hhh');
});
io.sockets.on('connection',function(socket){
socket.on('nickname',function(data){
console.log('The sever received the following nickname: ' +data);
});
});
index.html
<h1>Socket.IO Express Example</h1>
<form id="set-nickname">
<label for="nickname">Nickname:</label>
<input type="text" id="nickname">
<input type="submit" value="submit">
</form>
<script src="http://lib.sinaapp.com/js/jquery/1.9.1/jquery-1.9.1.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script type="text/javascript">
var socket = io.connect();
jQuery(function($){
var nickName = $('#nickname');
var setNacknameForm = $('#set-nickname');
setNacknameForm.submit(function(event){
event.preventDefalut();
socket.emit('nickname',nickName.val());
});
});
</script>
hhh can print in terminal browser but I enter words in browser, I click submit, nothing is printed in terminal.
I'm using express version 4.x
What should I do?
Related
I'm using Laravel and my directory structure is like below:
/example.com
/server.js
/node_modules
/css
/js
/main/views/writemessage.blade.php
/main/views/socket.blade.php
/main/app/Http/Controllers/SocketController.php
my code in server.js is:
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
io.set('origins', '*:*');
var redis = require('redis');
var cors = require('cors');
app.use(cors());
server.listen(8890);
io.on('connection', function (socket) {
console.log("new client connected");
var redisClient = redis.createClient();
redisClient.subscribe('message');
redisClient.on("message", function(channel, message) {
console.log("mew message in queue "+ message + "channel");
socket.emit(channel, message);
});
socket.on('disconnect', function() {
console.log('Disconnected!!!');
redisClient.quit();
});
});
my code in writemessage.blade.php is:
#extends('_template.default')
#section('main-content')
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js"></script>
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2" >
<div id="messages" ></div>
</div>
</div>
</div>
<script>
var socket = io.connect('https://example.com:8890', {secure: true});
socket.on('message', function (data) {
console.log('YES!!!!!!!!!!');
$( "#messages" ).append( "<p>"+data+"</p>" );
});
</script>
#endsection
my code in socket.blade.php is:
#extends('_template.default')
#section('main-content')
<div class="container">
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="panel panel-default">
<div class="panel-heading">Send message</div>
<form action="sendmessage" method="POST">
<input type="text" name="message" >
<input type="submit" value="send">
{{csrf_field()}}
</form>
</div>
</div>
</div>
</div>
#endsection
When I was in Windows it was returning CORS issues, but now when I'm using Linux it doesn't return that error but it doesn't return anything in console.
Also redis is running...but when I run node server.js it doesn't even print Connected nor Disconnected messages in console. Where my problem is from? Is it from url? I say url because when I check the Network Monitor in firefox I see that it is saying The connection used to fetch this resource was not secure. Have I done something wrong? Or should I do something more? How can test where the problem is from?
BTW my node version: 6.14.3 and my npm version: 3.10.10
Thanks
node.js socket.io code was correct but still got error ?
....................................................................................................................................
app.js
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');
});
users = {};
io.on('connection', function(socket){
console.log('Connected');
socket.on('setUsername', function(data){
if(users.indexOf(data) > -1)
{
socket.emit('userExists', data + ' is not avariable. please use other');
}
else
{
users.push(data);
socket.emit('userSet', {username: data});
}
})
socket.on('msg', function(data){
io.sockets.emit('newmsg', data);
})
});
http.listen(3000, function(){
console.log('start server on port :3000');
});
....................................................................................................................................
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Real time App chat</title>
</head>
<body>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.4/socket.io.js"></script>
<script type="text/javascript">
var socket = io();
function setUsername(){
socket.emit('setUsername', document.getElementByid('name').value);
};
var user;
socket.on('userExists', function(data){
document.getElementByid('error-container').innerHTML = data;
});
socket.on('userSet', function(data){
user = data.username;
document.body.innerHTML = '<input type="text" id="message">\
<button type="button" name="button" onclick="sendMessage()">ส่ง</button>\
<div id="message-container"></div>';
});
function sendMessage(){
var msg = document.getElementByid('message').value;
if(msg)
{
socket.emit('msg', {message: msg, user: user});
}
}
socket.on('newmsg', function(data){
if(user)
{
document.getElementByid('message-container').innerHTML += '<div><b>' + data.user + '</b>:' + data.message + '</div>';
}
})
</script>
<div id="error-container" ></div>
<input id="name" type="text" name="name" value="" placeholder="please set your name">
<button type="button" name="button" onclick="setUsername()">Start Chat</button>
</body>
</html>
When I load by node app.js, it is working good.
When I access to my-domain.com:3000, it shows the form.
But when I tried to fill data into "type text" id="name" and press button I get 2 errors.
How can i do for fixed it ?
You have a typo error in your code "index.html" in this function:
function setUsername(){
socket.emit('setUsername', document.getElementByid('name').value);
};
should be :
function setUsername(){
socket.emit('setUsername',document.getElementById('name').value);
};
document.getElementById('name') the 'i' of id should be uppercase
js code. which is a server file
while i am running this below code it is not sending messages when i click the button.
var express = require('express');
var socket = require('socket.io');
var app = express();
var server = app.listen(8000,function(){
console.log("The server is listening on the port 8000");
});
app.use(express.static('public'));
var io = socket(server);
io.on('connection', function(socket){
socket.on("chat", function(data){
io.sockets.emit("chat", data);
});
});
here is my index.html code which also contains
and css file which i am not included here
<!DOCTYPE html>
<html>
<head>
<title>my first chat app</title>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js">
</script>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="mario-chat">
<div id="chat-window">
<div id="output"></div>
<div id="feedback"></div>
</div>
<input id="handle" type="text" placeholder="Handle"/>
<input id="message" type="message" placeholder="Message"/>
<button id="send">Send</button>
</div>
<script src="/chat.js"></script>
</body>
</html>
the above code include a stylesheet.css file for looking good.
here is my chat.js file which is client side functionalities.
var socket = io.connect("http://localhost:8000");
var message = document.getElementById("message");
var handle = document.getElementById("handle");
var btn = document.getElementById("send");
var output = document.getElementById("output");
var feedback = document.getElementById("feedback");
btn.addEventListener("click",function(){
socket.emit("chat", {message:message.value,handle:handle.value});
});
socket.on("chat", function(data){
output.innerHTML += '<p><strong>' + data.handle + ':</strong>' +
data.message + '</p>';
});
please rectify me where i am doing mistakes
thanks in advance.
In your client code socket must be created with ws protocol. So,
io.connect("http://localhost:8000"); should be io.connect("ws://localhost:8000");
I'm walking through the Socket.io tutorial on creating a chat room, and I'm having trouble getting my app to log the chat message to the console.
The app is logging when a user connects & disconnects, but it is not logging when a message is passed through.
Any thoughts?
The relevant parts of my index.html page:
<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;
});
</script>
<body>
<ul id="messages"><ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
</body>
My index.js file:
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.use(express.static('public'));
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
console.log('a user connected');
socket.on('disconnect', function(){
console.log('user disconnected');
});
socket.on('chat message', function(msg) {
console.log("message: " + msg);
});
});
I've gotten it to work!
Steps to solution:
- separate the script tag with the event listener into a separate JS file
- include that JS file in the same place the script tag was originally
- load the chatListener when the document is ready
My files now look like this and everything works beautifully:
index.html:
<script src="/socket.io/socket.io.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script src="main.js"></script>
<body>
<ul id="messages"><ul>
<form action="">
<input class="chat" id="m" autocomplete="off" />
<input class="btn" type="submit" value="Send" />
</form>
</body>
index.js: nothing changed
main.js:
var socket = io();
var chatListener = function() {
$('form').submit(function() {
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
}
$(document).ready(function() {
chatListener();
})
In the end, I think it was a beginner's JS mistake; I was loading the script at the top of the page (as the tutorial suggested), and the event listener on the form was never registering.
I've Written This script for the server
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);
});
});
And This Is The Chatting Page
<html>
<head>
<title>Chat Program</title>
<style>
#chat{
height:400px;
}
</style>
<script src="http://code.jquery.com/jquery-latest-min.js"></script>
<script src="/node_modules/socket.io/node_modules/socket.io-client/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>
</head>
<body>
<div id="chat"></div>
<form id="send-message">
<input size="35" id="message"></input>
<input type="submit"></input>
</form>
</body>
</html>
When I Run The script from the console it runs well but when i write something in the chatting box nothing happen... I Don't Know Why But i think that the folder which i downloaded from "npm install socket.io-client" have a problem.
This Line ==> <script src="/node_modules/socket.io/node_modules/socket.io-client/socket.io.js"></script>I Think The Problem is here as the whole code is proper and right (I think)
hint : I'm Node.js beginner
You dont have express configured to serve the file. You have 2 options. You can:
configure express to serve that file explicitly
add this to your app file:
app.get('/socket.io.js' , function(req,res){
res.sendfile(__dirname + '/node_modules/socket.io/node_modules/socket.io-client/socket.io.js');
});
and switch your html script to:
<script src="/socket.io.js"></script>
configure express to server any file in a directory (see this)