In my Socket app, I'm trying to send programming code as a message to another client. If run the HTML only it shows the Ace editor perfectly. But when I run node app.js the ace editor doesn't work.I have downloaded ace-builds and installed npm ace-code-editor in the app, but nothing changes here is my code
app.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var port = process.env.PORT || 3000;
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);
io.emit('chat message', msg);
});
});
http.listen(port, function () {
console.log('listening on *:' + port);
});
index.html
<html>
<head>
<title>Socket.IO </title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
#m {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
</style>
<script src="/ace-builds/src-noconflict/ace.js" type="text/javascript" charset="utf-8"></script>
<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
var editor = window.ace.edit("m");
editor.setTheme("ace/theme/monokai");
editor.session.setMode("ace/mode/javascript");
$(function () {
var socket = io();
var myvar = setInterval(task, 100)
function task() {
var code=editor.getValue();
socket.emit('chat message',code);
}
socket.on('chat message', function (msg) {
editor.setValue("the new text here");
});
});
</script>
</head>
<body>
<div id="m">function foo(items) {
var x = "All this is syntax highlighted";
return x;
} </div>
</body>
</html>
Need a solution
you are calling window.ace.edit("m"); before that element becomes available.
Move script tag to the end of the file, or move ace initialization into $ call.
Related
I am trying to implement socket.io within an electron app. Following previous advice on a question I followed this chat app example https://socket.io/get-started/chat/ and then tried to turn it into an electron app. However it is like the functionality doesn't exist now, what am I doing wrong? The app launches but I only see the front end I can type and submit but nothing comes back. The code is as follow
main.js
const { app, BrowserWindow } = require('electron')
function createWindow () {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true
}
})
win.loadFile('index.html')
}
app.whenReady().then(createWindow)
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow()
}
})
index.js
const app = require('express')();
const http = require('http').createServer(app);
const io = require('socket.io')(http);
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
io.on('connection', (socket) => {
console.log('a user connected');
socket.on('chat message', (msg) => {
io.emit('chat message', msg)
});
});
index.html
<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();
var messages = document.getElementById('messages');
var form = document.getElementById('form');
var input = document.getElementById('input');
form.addEventListener('submit', function (e) {
e.preventDefault();
if (input.value) {
socket.emit('chat message', input.value);
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);
});
</script>
</body>
If I do node index.js it functions perfectly (I took the listen on port 3000 out in this question) However npm start to use as an electron app does not. Please Help!!!!!
I've seen many questions and none of them fix my problem.
Here's my JS (app.js) code:
var express = require('express');
var app = express();
var serv = require('http').Server(app);
app.get('/', function(req, res) {
res.sendFile(__dirname + '/client/index.html');
});
app.use('/client', express.static(__dirname + '/client'));
serv.listen(2000);
console.log('Server has started.');
var socket_list = {};
var io = require('socket.io')(serv, {});
io.sockets.on('connection', function(socket) {
console.log('Socket Connection');
socket.id = Math.random();
socket.x = 0;
socket.y = 0;
socket_list = socket.id = socket;
});
setInterval(function() {
for(var i in socket_list) {
var socket = socket_list[i];
socket.x++;
socket.y++;
socket.emit('newPosition', {
x: socket.x,
y: socket.y
});
}
}, 1000/25);
Here is my HTML (index.html) code:
<!DOCTYPE html>
<html>
<head>
<title>Multiplayer | HTML5</title>
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
</head>
<body>
<canvas id="ctx" width="512" height="512" style="border: 1px solid #000;"></canvas>
<script type="text/javascript">
var ctx = document.getElementById('ctx').getContext('2d');
ctx.font = '24px Calibri';
var socket = io();
socket.on('newPosition', function(data) {
ctx.clearRect(0,0,500,500);
ctx.fillText('P', data.x, data.y);
})
</script>
</body>
</html>
I'm following this tutorial: https://www.youtube.com/watch?v=_GioD4LpjMw&feature=youtu.be
It's 3 years old but everything is going smoothly until 4:47 in the video ^^.
Using the exact same code above ^^ I get this:
You are replacing Socket list object with a Socket object. Also use io.on.
io.sockets.on('connection', function(socket) {
console.log('Socket Connection');
socket.id = Math.random();
socket.x = 0;
socket.y = 0;
socket_list = socket.id = socket;
});
You need to change it to,
io.on('connection', function(socket) {//use io.on
console.log('Socket Connection');
socket.id = Math.random();
socket.x = 0;
socket.y = 0;
socket_list[socket.id] = socket;//fix this error
});
Change io.emit to socket.emit.
socket.emit('newPosition', {
x: socket.x,
y: socket.y
});
When a user clicks an html button (#new) I want to store their socket.id into an array (userQueue) on my node server but I'm having trouble figuring out how to do this. Do I need to set up a post request or is there a way through socket.io?
App.js (Server):
// App setup
var express = require('express'),
socket = require('socket.io'),
app = express(),
bodyParser = require("body-parser");
var server = app.listen(3000, function() {
console.log('listening to requests on port 3000');
});
var io = socket(server);
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static('public'));
// Room Logic
var userQueue = [];
io.on('connection', function(socket) {
console.log('made socket connection', socket.id);
socket.on('chat', function(data) {
io.sockets.emit('chat', data);
});
socket.on('typing', function(data) {
socket.broadcast.emit('typing', data);
});
});
Chat.js (client side):
// Make connection
var socket = io.connect('http://localhost:3000');
// Query DOM
var message = document.getElementById('message');
handle = document.getElementById('handle'),
btn = document.getElementById('send'),
btnNew = document.getElementById('new'),
output = document.getElementById('output'),
feedback = document.getElementById('feedback');
// Emit events
btn.addEventListener('click', function(){
socket.emit('chat', {
message: message.value,
handle: handle.value
});
});
message.addEventListener('keypress', function() {
socket.emit('typing', handle.value);
});
// Listen for events
socket.on('chat', function(data) {
feedback.innerHTML = ""
output.innerHTML += '<p><strong>' + data.handle + ':</strong>' + data.message + '</p>'
});
// Emit 'is typing'
socket.on('typing', function(data) {
feedback.innerHTML = '<p><em>' + data + ' is typing a message...</em></p>'
});
Index.html:
<!DOCTYPE html>
<html>
<head>
<title>WebSockets 101</title>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js"></script>
<link rel="stylesheet" type="text/css" href="/styles.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="text" placeholder="Message">
<button id="send">Send</button>
<button id="new">New</button>
</div>
<script type="text/javascript" src="/chat.js"></script>
</body>
</html>
I believe that a post request will probably work as well, but if you want to simply work with socket.io you can consider doing something similar to your chat event by adding this in your chat.js:
btnNew.addEventListener('click', function() {
socket.emit('new user', socket.id);
});
And on the server side, app.js:
socket.on('new user', function(id) {
userQueue.push(id);
});
And it should be stored in the array. Hope this helps!
I want send simple message to node.js console from html. But number is working , string and any characters not working,
Display message is
message: NaN
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile('sample.html', {
root:'/home/deneebo/Documents/apidevelopment/nodejs'});
});
io.on('connection', function(socket) {
socket.on('chat message', function(msg) {
console.log('message: ', + msg);});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
below html code
<!doctype html>
<html>
<head>
<title>Socket.IO chat</title>
</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 src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
var socket = io();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
alert($('#m').val());
$('#m').val('');
return false;
});
</script>
</body>
</html>
I tried your code my local work well
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendfile('stack.html', {root: __dirname });
});
io.on('connection', function(socket) {
socket.on('chat message', function(msg) {
console.log('message: ', msg);}); //Remove + from here
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
I am just trying to do a very basic chat application with socket.io and node. I am unable to see anything get printed out to my screen, and cannot find any errors. Appreciate the help!
Thanks.
app.js
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
server.listen(3000);
console.log('Server running...');
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);
});
});
index.html
<html>
<title>Chat Test</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 ="https://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>
</body>
</head>
</html>
When using jQuery, you must spell it jQuery, not JQuery or you could just use the built-in alias $.
This should have shown an error in the debug console of the browser which is something you should learn to look for to see your own errors.
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/>");
});
});
After fixing this and then running your code and accessing http://localhost:3000, your app works just fine for me. Anything submitted in the form is broadcast to all connected clients.