So I am trying to add require.js to my project that I am using jQuery and Socket.io to create but I keep getting this error.
I was wondering what is going on here? I am adding my code like this
<script src="js/require.js"></script>
<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 $nickForm = $('#setNick');
var $nickError = $('#nickError');
var $nickBox = $('#nickname');
var $users = $('#users');
var $messageForm = $('#send-message');
var $messageBox = $('#message');
var $chat = $('#chat');
$nickForm.submit(function (e) {
e.preventDefault();
socket.emit('new user', $nickBox.val(), function (data) {
if (data) {
$('#nickWrap').hide();
$('#contentWrap').show();
} else {
$nickError.html('Name is taken! Choose a New one!');
}
});
$nickBox.val('');
});
socket.on('usernames', function (data) {
var html = '';
for (var i = 0; i < data.length; i++) {
html += data[i] + '<br/>'
}
$users.html(html);
});
$messageForm.submit(function (e) {
e.preventDefault();
socket.emit('send message', $messageBox.val(), function (data) {
$chat.append('<span class = "error"' + data + "</span><br/>");
});
$messageBox.val('');
});
socket.on('new message', function (data) {
$chat.append('<span class= "msg"<b>' + data.nick + ': </b>' + data.msg + "<span/><br/>");
});
socket.on('whisper', function (data) {
$chat.append('<span class = "whisper"<b>' + data.nick + ': </b>' + data.msg + "</span><br/>");
});
});
</script>
Edit
Here is my server code
var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server),
users ={};
server.listen(3000);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
res.sendFile(__filename + 'js/bower_components/crypto-js/crypto-js.js');
});
io.sockets.on('connection', function(socket){
socket.on('new user', function(data, callback){
if(data in users) {
callback(false);
} else{
callback(true);
socket.nickname = data;
users[socket.nickname] = socket
updateNames();
}
});
function updateNames(){
io.sockets.emit('usernames', Object.keys(users));
}
socket.on('send message', function(data, callback){
var msg = data.trim();
if(msg.substr(0,3) === '/w '){
msg = msg.substr(3);
var ind = msg.indexOf(' ');
if(ind !== -1){
var name = msg.substr(0, ind);
var msg = msg.substr(ind + 1);
if(name in users){
users[name].emit('whisper', {msg: msg, nick: socket.nickname});
console.log('hi');
} else{
callback('Error! Enter a valid user!');
}
}else{
callback("Error! Enter a pm");
}
} else {
io.sockets.emit('new message', {msg: msg, nick: socket.nickname});
}
});
socket.on('disconnect', function(data){
if(!socket.nickname) return;
delete users[socket.nickname];
updateNames();
});
});
This error basically means that js/require.js does not contain valid JS code.
Double check that its not including any extraneous code or characters.
Related
I'm trying to make a chat application using spring boot and I am stuck. This is my Frontend (custom.js) code. I want to make a separate chat view for every specific user since all user's chat which is entered in this are showing on the same view. I have given an image link in this for a better explanation if anyone could help...
custom.js
let $chatHistory;
let $button;
let $textarea;
let $chatHistoryList;
function init() {
cacheDOM();
bindEvents();
}
function bindEvents() {
$button.on('click', addMessage.bind(this));
$textarea.on('keyup', addMessageEnter.bind(this));
}
function cacheDOM() {
$chatHistory = $('.chat-history');
$button = $('#sendBtn');
$textarea = $('#message-to-send');
$chatHistoryList = $chatHistory.find('ul');
}
function render(message, userName) {
scrollToBottom();
// responses
var templateResponse = Handlebars.compile($("#message-response-template").html());
var contextResponse = {
response: message,
time: getCurrentTime(),
userName: userName
};
setTimeout(function () {
$chatHistoryList.append(templateResponse(contextResponse));
scrollToBottom();
}.bind(this), 1500);
}
function sendMessage(message) {
let username = $('#userName').val();
console.log(username)
sendMsg(username, message);
scrollToBottom();
if (message.trim() !== '') {
var template = Handlebars.compile($("#message-template").html());
var context = {
messageOutput: message,
time: getCurrentTime(),
toUserName: selectedUser
};
$chatHistoryList.append(template(context));
scrollToBottom();
$textarea.val('');
}
}
function scrollToBottom() {
$chatHistory.scrollTop($chatHistory[0].scrollHeight);
}
function getCurrentTime() {
return new Date().toLocaleTimeString().replace(/([\d]+:[\d]{2})(:[\d]{2})(.*)/, "$1$3");
}
function addMessage() {
sendMessage($textarea.val());
}
function addMessageEnter(event) {
// enter was pressed
if (event.keyCode === 13) {
addMessage();
}
}
init();
chat.js
const url = 'http://localhost:8080';
let stompClient;
let selectedUser;
let newMessages = new Map();
function connectToChat(userName) {
console.log("connecting to chat...")
let socket = new SockJS(url + '/chat');
stompClient = Stomp.over(socket);
stompClient.connect({}, function (frame) {
console.log("connected to: " + frame);
stompClient.subscribe("/topic/messages/" + userName, function (response) {
let data = JSON.parse(response.body);
if (selectedUser === data.fromLogin) {
render(data.message, data.fromLogin);
} else {
newMessages.set(data.fromLogin, data.message);
$('#userNameAppender_' + data.fromLogin).append('<span id="newMessage_' + data.fromLogin + '" style="color: red">+1</span>');
}
});
});
}
function sendMsg(from, text) {
stompClient.send("/app/chat/" + selectedUser, {}, JSON.stringify({
fromLogin: from,
message: text
}));
}
function registration() {
let userName = document.getElementById("userName").value;
$.get(url + "/registration/" + userName, function (response) {
connectToChat(userName);
}).fail(function (error) {
if (error.status === 400) {
alert("Login is already busy!")
}
})
}
function selectUser(userName) {
console.log("selecting users: " + userName);
selectedUser = userName;
let isNew = document.getElementById("newMessage_" + userName) !== null;
if (isNew) {
let element = document.getElementById("newMessage_" + userName);
element.parentNode.removeChild(element);
render(newMessages.get(userName), userName);
}
$('#selectedUserId').html('');
$('#selectedUserId').append('Chat with ' + userName);
}
function fetchAll() {
$.get(url + "/fetchAllUsers", function (response) {
let users = response;
let usersTemplateHTML = "";
for (let i = 0; i < users.length; i++) {
usersTemplateHTML = usersTemplateHTML + '<a href="#" onclick="selectUser(\'' + users[i] + '\')"><li class="clearfix">\n' +
' <img src="https://rtfm.co.ua/wp-content/plugins/all-in-one-seo-pack/images/default-user-image.png" width="55px" height="55px" alt="avatar" />\n' +
' <div class="about">\n' +
' <div id="userNameAppender_' + users[i] + '" class="name">' + users[i] + '</div>\n' +
' <div class="status">\n' +
' <i class="fa fa-circle offline"></i>\n' +
' </div>\n' +
' </div>\n' +
' </li></a>';
}
$('#usersList').html(usersTemplateHTML);
});
}
I'm not really expert yet, anyway thank you for helping me. I created a website with two different pages. Now I want to get two different chats, one for the first page and one for the second. I need to use socket.io. I've actually already implemented the code to get one working chat, but when I type something on this chat, the message appears even in the other. So this means that the two chats are linked each other. That is the problem because I want them to be indipendent. Id est I want them to work with their own pages which have got the send button, the input field for the message and the input field for your name. So the two pages can work alone, but i don't know how.
My code is divided into 2 pages: index.js and chat.js. Here there is Index.js:
var express = require('express');
var socket = require('socket.io');
//app setup
var app = express();
var server = app.listen(8080, function(){
console.log('ascoltando la richiesta alla porta 8080');
});
//static
app.use(express.static('public'));
//socket setup
var io = socket(server);
io.on('connection', function(socket){
console.log('fatta la connessione socket', socket.id);
socket.on('chat', function(data) {
io.emit('chat', data);
});
socket.on('typing', function(data) {
socket.broadcast.emit('typing', data);
});
});
And here there is the code placed in chat.js (which is the file linked in one html page, the other page is not currently linked with anything):
//connessione
var socket = io.connect('http://localhost:8080'); // è una variabile socket diversa da quella in index.js
//query
var message= document.getElementById('message');
var handle = document.getElementById('handle');
var button = document.getElementById('send');
var output = document.getElementById('output');
var feedback = document.getElementById('feedback');
//scrollbar sempre in basso
function updateScroll(){
var element = document.getElementById("output");
element.scrollTop = element.scrollHeight;
}
//emit eventi
button.addEventListener('click',function() {
socket.emit('chat', {
message: message.value,
handle: handle.value
});
});
message.addEventListener('keypress', function() {
socket.emit('typing', handle.value);
});
//listen eventi
socket.on('chat', function(data){
if (data.message !== "" & data.handle !== "") {
if (handle.value === data.handle) {
feedback.innerHTML= "" ;
output.innerHTML +='<p id=inviato>' +'<span id="utente">'+'Tu' +'</span> <br> ' + data.message +'</p> <br>';
updateScroll();
document.getElementById('message').value='';
} else {
feedback.innerHTML= "" ;
output.innerHTML +='<p id=ricevuto>' +'<span id="utente">'+data.handle +'</span> <br> ' + data.message +'</p> <br>';
updateScroll();
document.getElementById('message').value='';
}
}
});
socket.on('typing', function(data) {
feedback.innerHTML = '<p>'+ data + ' sta scrivendo...' + io.engine.clientsCount;
});
Thank you so much
thank you but I've probably not understood because it doesn't work anymore: when i press the send button, nothing happens.
here there are the two codes updated.
index.js:
var express = require('express');
var io = require('socket.io')(server);
//app setup
var app = express();
var server = app.listen(8080, function(){
console.log('ascoltando la richiesta alla porta 8080');
});
//static
app.use(express.static('public'));
//socket setup
var room1 = io.of('/room1');
var room2 = io.of('/room2');
room1.on('connection', function(socket){
console.log('fatta la connessione socket', socket.id);
socket.on('chat', function(data) {
io.emit('chat', data);
});
socket.on('typing', function(data) {
socket.broadcast.emit('typing', data);
});
});
room2.on('connection', function(socket){
console.log('fatta la connessione socket', socket.id);
socket.on('chat', function(data) {
io.emit('chat', data);
});
socket.on('typing', function(data) {
socket.broadcast.emit('typing', data);
});
});
chat.js:
//connessione
var socket = io.connect('http://localhost:8080/room1');// è una variabile socket diversa da quella in index.js
//query
var message= document.getElementById('message');
var handle = document.getElementById('handle');
var button = document.getElementById('send');
var output = document.getElementById('output');
var feedback = document.getElementById('feedback');
//scrollbar sempre in basso
function updateScroll(){
var element = document.getElementById("output");
element.scrollTop = element.scrollHeight;
}
//emit eventi
button.addEventListener('click',function() {
socket.emit('chat', {
message: message.value,
handle: handle.value
});
});
message.addEventListener('keypress', function() {
socket.emit('typing', handle.value);
});
//listen eventi
socket.on('chat', function(data){
if (data.message !== "" & data.handle !== "") {
if (handle.value === data.handle) {
feedback.innerHTML= "" ;
output.innerHTML +='<p id=inviato>' +'<span id="utente">'+'Tu' +'</span> <br> ' + data.message +'</p> <br>';
updateScroll();
document.getElementById('message').value='';
} else {
feedback.innerHTML= "" ;
output.innerHTML +='<p id=ricevuto>' +'<span id="utente">'+data.handle +'</span> <br> ' + data.message +'</p> <br>';
updateScroll();
document.getElementById('message').value='';
}
}
});
socket.on('typing', function(data) {
feedback.innerHTML = '<p>'+ data + ' sta scrivendo...' + io.engine.clientsCount;
});
console.log('clear arr: ' + clearnUP.join('-'));
My question is, when closing client, why is clearUp empty?
/* Beginners nodejs, fx, From China. */
var net = require('net');
var server = net.createServer();
var clients = [];
server.on('connection', function(client) {
client.write('hi\n\r');
clients.push(client);
client.on('data', function(data) {
printMsg(data, client);
});
client.on('end', function() {
clients.splice(clients.indexOf(client), 1);
});
client.on('error', function() {
console.log(err);
})
function printMsg(msg, client) {
var clearnUP = [];
for (var i = 0; i < clients.length; i++) {
client != clients[i] && (clients[i].writable ? clients[i].write(client.remotePort + ': ' + msg.toString() + '\n\r') : clearnUP.push(clients[i]) && clients[i].destroy() && clearnUP); // diswritable client push to clearUp<Array>
}
console.log(client.remotePort + ': ' + msg.toString());
console.log('clear arr: ' + clearnUP.join('-')); //when closed client, why clearUp is empty!!
}
//console.log(client);
}).listen(1220);
Socket.io is having issues connecting up.
This is my Server code:
function chatserver(){
var express = require('express'),
app = express(),
server = require('http').createServer(app).listen(app.get('port'),function(){
console.log('Express server listening on port '+ app.get('port'));
});
var io = require('socket.io').listen(server),
users = {};
io.sockets.on('connection', function(socket){
socket.on('new user', function(data, callback){
if (data in users){
callback(false);
} else{
callback(true);
socket.nickname = data;
users[socket.nickname] = socket;
updateNicknames();
}
});
function updateNicknames(){
io.sockets.emit('usernames', Object.keys(users));
}
socket.on('send message', function(data, callback){
var msg = data.trim();
console.log('after trimming message is: ' + msg);
if(msg.substr(0,3) === '/w '){
msg = msg.substr(3);
var ind = msg.indexOf(' ');
if(ind !== -1){
var name = msg.substring(0, ind);
var msg = msg.substring(ind + 1);
if(name in users){
users[name].emit('whisper', {msg: msg, nick: socket.nickname});
console.log('message sent is: ' + msg);
console.log('Whisper!');
} else{
callback('Error! Enter a valid user.');
}
} else{
callback('Error! Please enter a message for your whisper.');
}
} else{
io.sockets.emit('new message', {msg: msg, nick: socket.nickname});
}
});
socket.on('disconnect', function(data){
if(!socket.nickname) return;
delete users[socket.nickname];
updateNicknames();
});
});
}
My HTML script code:
jQuery(function($){
var socket = io.connect('js/node_modules/socket.io/node_modules/socket.io-client/dist/socket.io.js');
var $nickForm = $('#setNick');
var $nickError = $('#nickError');
var $nickBox = $('#nickname');
var $users = $('#users');
var $messageForm = $('#send-message');
var $messageBox = $('#message');
var $chat = $('#chat');
$nickForm.submit(function(e){
e.preventDefault();
socket.emit('new user', $nickBox.val(), function(data){
if(data){
$('#nickWrap').hide();
$('#contentWrap').show();
} else{
$nickError.html('That username is already taken! Try again.');
}
});
$nickBox.val('');
});
socket.on('usernames', function(data){
var html = '';
for(i=0; i < data.length; i++){
html += data[i] + '<br/>'
}
$users.html(html);
});
$messageForm.submit(function(e){
e.preventDefault();
socket.emit('send message', $messageBox.val(), function(data){
$chat.append('<span class="error">' + data + "</span><br/>");
});
$messageBox.val('');
});
socket.on('new message', function(data){
$chat.append('<span class="msg"><b>' + data.nick + ': </b>' + data.msg + "</span><br/>");
});
socket.on('whisper', function(data){
$chat.append('<span class="whisper"><b>' + data.nick + ': </b>' + data.msg + "</span><br/>");
});
});
When I load up the website at first it's OK. But as soon as I click the chat box, in inspect elements/console I get to see "GET http://'js':5001/socket.io/1/?.." error appear. Please advise.
In server code, change this:
server = require('http').createServer(app).listen(port),
io = require('socket.io').listen(server),
to
var server = http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
var io = require('socket.io').listen(server);
If you are in http server not express.io server, use this:
app.listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
Your main problem is client Jquery script.
var socket = io.connect('js/node_modules/socket.io/node_modules/socket.io-client/dist/socket.io.js');
It is not the proper way to server socket.io.js to client.
You need to change it to http://<ip/domain>:<port>/socket.io/socket.io.js
If Socket.io Server listens properly to your HTTP server, it will automatically serve the client file to via http://<ip/domain>:<port>/socket.io/socket.io.js. You don't need to find it or copy in public accessible folder as resources/js/socket.io.js & serve it manually.
Code sample Express 3.x -
Express 3 requires that you instantiate a http.Server to attach socket.io to first
var express = require('express')
, http = require('http');
//make sure you keep this order
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);
//...
server.listen(8000);
Happy Coding :)
I have a simple tcp connection server in nodejs + socket.io can send data to the server but I have no comeback.
excuse my english I'm from Brazil
see the code.
client code:
if(newY !== ymouse || newX !== xmouse)
{
socket.emit('chat', {playerX: playerX, playerY: playerY});
}
socket.on('chat',
function (data)
{
console.log(data)
// $("p#data_recieved").append("<br />\r\n [position] {" + data.msgr + ": playerX = " + data.playerX + ", playerY = " + data.playerY + "}");
document.getElementById("vy").innerHTML = data.X;
document.getElementById("vx").innerHTML = data.y;
}
server code:
var io = require('socket.io').listen(8000);
io.sockets.on('connection',
function (socket)
{
socket.on('chat',
function (data)
{
var sender = 'unregistered';
socket.get('nickname',
function (err, name)
{
console.log('Chat message by ', name);
console.log('error ', err);
console.log('X: ' + data.playerX);
console.log('Y: ' + data.playerY);
sender = name;
});
socket.broadcast.emit('chat', { playerX : data.playerX, playerY : data.playerY, msg : data, msgr : sender});
});
socket.on('position',
function (data)
{
var sender = 'unregistered';
socket.get('nickname',
function (err, name)
{
sender = name;
});
if(sender == 'unregistered')
return;
var playerX = data.playerX;
var playerY = data.playerY;
socket.broadcast.emit('position', {msgr : sender, playerX : playerX, playerY : data.playerY});
});
socket.on('register',
function (name)
{
socket.set('nickname', name,
function ()
{
io.sockets.emit('chat', {msg : "naay nag apil2! si " + name + '!', msgr : "mr. server"});
});
});
});
how can you see I can
send data to the server but
no response
server seems to work well
I leave an example of a simple connection in which you can inspire
Server:
var simple = io
.sockets
.on('connection', function(socket) {
socket.on('message', function(data) {
socket.broadcast.send(data);
});
socket.on('disconnect', function() {
// handle disconnect
});
});
Client:
var socket = io.connect();
var content = $('#simple-content');
socket.on('connect', function() {
$('#simple-form').css('display', 'block');
content.append($('<p>').text('Connected'));
});
socket.on('message', function(msg) {
content.append($('<p>').text(msg)
.append($('<em>').text(' from server')));
});
$('#simple-form').submit(function(e) {
e.preventDefault();
var textObj = $('#simple-text');
var msg = textObj.val();
textObj.val('');
content.append($('<p>').text(msg)
.append($('<em>').text(' from me')));
socket.send(msg);
});
I hope it will be helpful!