I am trying to send Message to Particular Room, but it doesn't work and It sends message to all room along with my message being received twice from my name and with first chat room user name. Message from 1 Room is broadcasted to all Chat Room.
I have used Example Code from here- https://github.com/kataras/iris/blob/master/_examples/websocket/secure/main.go. and
https://github.com/kataras/iris/blob/master/_examples/websocket/native-messages/main.go
Below is the Code, I am using, that is giving me the error :
var myChatRoom = strconv.Itoa(room.ID)
ws := websocket.New(websocket.Config{})
ws.OnConnection(func(c websocket.Connection) {
c.Join(myChatRoom)
c.To(myChatRoom).EmitMessage([]byte(user.(users).Username + " has Joined Chat!"))
c.OnMessage(func(data []byte) {
message := string(data)
if message == "leave" {
c.Leave(myChatRoom)
c.To(myChatRoom).EmitMessage([]byte(user.(users).Username + " has Left Chat!"))
return
}
c.To(myChatRoom).EmitMessage([]byte(user.(users).Username + ": " + message))
})
c.OnDisconnect(func() {
fmt.Printf("Connection with ID: %s has been disconnected!\n", c.ID())
})
})
HTML Code:
<div id="messages" style="border-width: 1px; border-style: solid; height: 200px;overflow:auto"></div>
<input type="text" id="messageTxt" />
<button type="button" id="sendBtn">Send</button>
Javascript Code:
<script>
var messageTxt;
var messages;
var HOST = 'localhost'
jQuery(function() {
messageTxt = jQuery("#messageTxt");
messages = jQuery("#messages");
w = new WebSocket("ws://" + HOST + "/my_endpoint");
w.onopen = function() {
console.log("Websocket connection enstablished");
};
w.onclose = function() {
appendMessage(jQuery("<div><center><h3>Disconnected</h3></center></div>"));
};
w.onmessage = function(message) {
console.log("Message Appended: " + message)
appendMessage(jQuery("<div>" + message.data + "</div>"));
};
jQuery("#sendBtn").click(function() {
w.send(messageTxt.val().toString());
messageTxt.val("");
});
})
function appendMessage(messageDiv) {
messageDiv.appendTo(jQuery("#messages"));
}
</script>
Error:
It sends message to all ROOM and not specific Room.
User who created room first automatically joins all the ROOM
People sending message in other ROOM see their message being Repeated/cloned in their ROOM by "FirstUser" who created first room in chat. (Irrespective of whether he is member of the chat group or not)
Expecting:
People can send/receive message to only those room where they have joined.
First User should not be able to join CHATRoom automatically.
People should not see their message being repeated again with "FirstUser" name.
It was a tiny bug, fixed just moments ago. Please upgrade with:
go get -u github.com/kataras/iris
A new release "v10.6.3" was also pushed.
Thank you a lot #Belarus, you're great!
Sincerely,
Gerasimos Maropoulos,
Author of the Iris web framework.
Related
I'm working on a project where I have a twitter bot that reply every tweets in its acount.
Here's my code:
var replybot = function() {
//The word that we are going to search in tweets
var word = 'hello';
//Variables to store the twitter user id and screen name to make a reply
var id_str, screen_name;
console.log('Bot started looking for the word ' + word + '.');
stream.on('tweet', tweetEvent );
function tweetEvent(tweet) {
var info_text = tweet.text;
if (info_text.indexOf(word) > -1) {
console.log(tweet.text); //Displays the tweet with the word
//We store the twitter id and the user screen name to make a reply
id_str = tweet.id_str;
screen_name = tweet.user.screen_name;
console.log('need do it once');
//Now we are going to reply the tweet
Twitter.post('statuses/update', {in_reply_to_status_id: id_str,
status: '#' + screen_name + ' I think you mean "goodbye"'},
function(error, tweet, response){
if(error) {
console.log(' Error');
}
else{
console.log('. Success!!!');
} // Tweet body
});
}
}
console.log('done');
}
replybot();
// 'reply' a tweet in every 25 minutes
setInterval(replybot, 1500000);
Im following this repo to work: https://github.com/ttezel/twit .
But i had an issue : when i run this code above, the bot reply so many time on one tweet, and i dont know why.
Although i've set interval for this function.
Im new with node and any help would be great ! Thanks
Oh so sorry i got a loop forever in here :
function(error, tweet, response)
it shouldn't be tweet arg
Im currently switching my application from using Socket.io to HTML5 WebSockets. I'm assuming that my problem lies within the first couple lines of both the client and server. My browser keeps on replying with a 426 (Upgrade Required) status when I test my app on localhost. Please shed some light on my problem...
Server Code
"use strict";
var session = require('./chat-session'),
serveStatic = require('serve-static'),
server = require('http').createServer(),
WebSocketServer = require('ws').Server,
wss = new WebSocketServer({server: server, port: 8181}),
express = require('express'),
app = express();
// Sockets with real-time data
// io = require('socket.io').listen(server),
// mongoose = require('mongoose');
app.use(express.static(__dirname + '/public')); // used for external files on client
let storage = session.default; // cache object for storage
// Routing refers to determining how an application responds to a client request to a particular endpoint
app.get('/', function(req, res){
res.sendFile(__dirname + '/public/index.html');
});
wss.on('connection', function(client){
client.on('join', (name) => {
client.nickname = name;
// check to see if nickname has been taken, if so, give random name
if(storage.users.indexOf(client.nickname) !== -1) {client.nickname = randomName();}
// tell all chatters that a new user has entered the room
client.broadcast.emit("enter", "* " + client.nickname + " * has connected");
storage.users.forEach((user) => {
client.emit('add chatter', user);
});
client.broadcast.emit('add chatter', client.nickname);
storage.channels.general.messages.forEach((message) => {
client.emit("message", message.name + ": " + message.data, 'general');
});
storage.users.push(client.nickname);
});
client.on('message', (message, room) => {
var nickname = client.nickname;
client.broadcast.emit("message", nickname + ": " + message, room);
client.emit("me", message); // send message to self
storeMessage(nickname, message, room); // store the message in chat-session
console.log(nickname + ' said: ' + message + " in room " + room);
});
// When client switches between tabs (rooms)
client.on('switch', (room) => {
storage.channels[room].messages.forEach((message) => {
if (message.name === client.nickname) {
client.emit("me", message.data, room);
} else {
client.emit("message", message.name + ": " + message.data, room);
}
});
});
// client.on('disconnect', () => {
// client.emit('disconnect', "client")
// });
});
//const PORT = 8080;
//server.listen(PORT);
Client Code
// var server = io.connect("http://localhost:8080"); // connect to server
var server = new WebSocketServer("ws://localhost:8181");
var curRoom = $('.nav .active').attr('id'); // cache current room
server.on('connect', function(data){
nickname = prompt("What is your nickname?");
//while(nickname) TODO:make sure client cannot choose null
server.emit('join', nickname); // notify the server of the users nickname
});
//server.on('disconnect', function(data){
// server.emit('disconnect');
//});
// new chatter enters room
server.on('enter', function(data){
$('#messages').append($('<li style="background:#33cc33; color:white">').text(data));
});
// connected users section
server.on('add chatter', function(name){
var chatter = $('<li style="color:white; font-size:22px">' + name + '</li>').data('name', name);
$('#users').append(chatter);
});
// users' send message
server.on('message', function(message, room){
// only emit message to other users if they are in same channel
if (curRoom === room) {
$('#messages').append($('<li style="display:table; box-shadow: 6px 3px 8px grey;">').text(message));
play(); // invoke function to play sound to other clients
console.log('sound played here');
}
});
// differentiate how the client sees their message
server.on('me', function(message){
$('#messages').append($('<li style="background:#0066ff; color:white; display:table; box-shadow: 6px 3px 8px grey;">').text(message));
});
// Client submits message
$('#chat_form').submit(function(e){
var message = $("#chat_input").val();
server.emit('message', message, curRoom);
$('#chat_input').val(''); // Make input box blank for new message
return false; // prevents refresh of page after submit
});
Http 426 means that you are trying to connect unsupported web-socket version .
You can check in the client headers for supported version .
Refer to RFC for more detail
https://www.rfc-editor.org/rfc/rfc6455#section-4.2.2
This is my Signal R Client.
I get this error when i run my client.(0x800a139e - JavaScript runtime error: SignalR: Error loading hubs. Ensure your hubs reference is correct, e.g. .)
The exception comes from line $.connection.hub.start
There is a ServerHub class in a folder HUBS in my Server application which runs fine.
Can anyone help me out..
Thanks
<script src="~/Scripts/jquery.signalR-2.2.0.min.js"></script>
<script src="http://localhost:39670/MySignalRServer/signalr/hubs"></script>
var ChatHubProxy = $.hubConnection("http://localhost:39670/MySignalRServer/signalr/hubs");
var chat = ChatHubProxy.createHubProxy('ServerHub');
chat.on("addNewMessageToPage",function (name, message) {
// Add the message to the page.
$('#discussion').append('<li><strong>' + htmlEncode(name)
+ '</strong>: ' + htmlEncode(message) + '</li>');
});
$.connection.hub.start({jsonp:true}).done(function () {
$('#sendmessage').click(function () {
// Call the Send method on the hub.
chat.server.send($('#displayname').val(), $('#message').val());
alert("hiii");
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
});
});
Try change your code to :
<script src="~/Scripts/jquery.signalR-2.2.0.min.js"></script>
<script src="http://localhost:39670/MySignalRServer/signalr/hubs"></script>
var chat = $.connection.ServerHub; //here
chat.on("addNewMessageToPage", function(name, message) {
// Add the message to the page.
$('#discussion').append('<li><strong>' + htmlEncode(name)
+ '</strong>: ' + htmlEncode(message) + '</li>');
});
$.connection.hub.start().done(function() { //here
$('#sendmessage').click(function() {
// Call the Send method on the hub.
chat.server.send($('#displayname').val(), $('#message').val());
alert("hiii");
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
});
});
And make sure that this address is good - <script src="http://localhost:39670/MySignalRServer/signalr/hubs"></script>
I always use this - <script src="/signalr/hubs"></script>
And add HubName Attribute
[HubName("ServerHub")]
public class ServerHub : Hub
{
public string Send(string name, string message)
{
Clients.All.broadcastMessage(name, message);
return null;
}
}
or change this code :
var chat = $.connection.ServerHub;
to
var chat = $.connection.serverHub;
Demo project : https://github.com/czerwonkabartosz/SignalRDemo
I have run my nodeServer and Client sucessfully. But I want to connect its server to a proxy.
Here is the node client:
<html>
<head>
<script src="http://localhost:8000/socket.io/socket.io.js"></script>
<script src="http://code.jquery.com/jquery-1.6.2.min.js"></script>
<script>
var name = '';
var socket = io.connect('http://localhost:8000');
// at document read (runs only ones).
$(document).ready(function(){
// on click of the button (jquery thing)
// the things inside this clause happen only when
// the button is clicked.
$("button").click(function(){
// just some simple logging
$("p#log").html('sent message: ' + $("input#msg").val());
// send message on inputbox to server
socket.emit('chat', $("input#msg").val() );
// the server will recieve the message,
// then maybe do some processing, then it will
// broadcast it again. however, it will not
// send it to the original sender. the sender
// will be the browser that sends the msg.
// other browsers listening to the server will
// recieve the emitted message. therefore we will
// need to manually print this msg for the sender.
$("p#data_recieved").append("<br />\r\n" + name + ': ' + $("input#msg").val());
// then we empty the text on the input box.
$("input#msg").val('');
});
// ask for the name of the user, ask again if no name.
while (name == '') {
name = prompt("What's your name?","");
}
// send the name to the server, and the server's
// register wait will recieve this.
socket.emit('register', name );
});
// listen for chat event and recieve data
socket.on('chat', function (data) {
// print data (jquery thing)
$("p#data_recieved").append("<br />\r\n" + data.msgr + ': ' + data.msg);
// we log this event for fun :D
$("p#log").html('got message: ' + data.msg);
});
</script>
</head>
<body>
<input type="text" id="msg"></input><button>Click me</button>
<p id="log"></p>
<p id="data_recieved"></p>
</body>
</html>
Here is Server:
var check="check";
var io = require('socket.io').listen(8000);
// open the socket connection
io.sockets.on('connection', function (socket) {
// listen for the chat even. and will recieve
// data from the sender.
console.log('hello nahid');
socket.on('chat', function (data) {
// default value of the name of the sender.
var sender = 'unregistered';
check=sender;
// get the name of the sender
socket.get('nickname', function (err, name) {
console.log('Chat message by ', name);
console.log('error ', err);
sender = name;
});
// broadcast data recieved from the sender
// to others who are connected, but not
// from the original sender.
socket.broadcast.emit('chat', {
msg : data,
msgr : sender
});
});
// listen for user registrations
// then set the socket nickname to
socket.on('register', function (name) {
// make a nickname paramater for this socket
// and then set its value to the name recieved
// from the register even above. and then run
// the function that follows inside it.
socket.set('nickname', name, function () {
// this kind of emit will send to all! :D
io.sockets.emit('chat', {
msg : "naay nag apil2! si " + name + '!',
msgr : "mr. server"
});
});
});
});
They work well together. Now I want to have included server file into another html client like this:
<script type="text/javascript" src="nodeServer.js"></script>
In order to access variables in nodeServer.js. But The error "Uncaught ReferenceError: require is not defined "
What can I do to solve this and also I have this line code :
such that it knows what socket.io syntax is. But the error exists.
What should I do to make my html file know socket.io.js.
EDIT:
The last comment on the checked answer is what solved my issue. Thanks to #Houseman.
I'm pretty sure you can't just throw a Node.js file into a html DOM and expect it to work. Node.js files are run by Node.js, not by client-side html javascript.
This line <script src="http://localhost:8000/socket.io/socket.io.js"></script> is sufficient for loading the io object into your DOM, and make it accessible through javascript.
Remove this line:
<script type="text/javascript" src="nodeServer.js"></script>
, and you should be fine, if your server is running on port 8000. Your server code, however, doesn't seem to have the necessary components to actually run.
EDIT:
If you want to pass variables from your client to your server, or the other way around, use sockets, just like you're already doing.
I am using PubNub for in-app chat with Backbone and the javascript sdk. If I navigate to another view and return to the chat window, when I publish a message I receive it in duplicate. If I browse away again I receive messages in triplicate and so on..
I think I am subscribing again and again each time I return to the chat page - but I can't get the unsubscribe to work and I can't find any documentation on where else to subscribe from.
Is there a check I can use to see if I am already subscribed?
My code is:
// INIT
var channel = 'my_channel';
var pubnub = PUBNUB.init({
subscribe_key : 'demo',
publish_key : 'demo'
});
function chat(message) {
if (message.uid == "xxx") {
$("#convo").append('<div class="isaid">' + message.message + '</div><div class="clear clearfix"></div>');
} else {
$("#convo").append('<div class="hesaid">' + message.message + '</div><div class="clear clearfix"></div>');
}
}
pubnub.history({
channel : channel, // USER_ID Channel
limit : 30, // Load Last 50 Messages
callback : function(msgs) {
pubnub.each( msgs[0], chat );
}
});
pubnub.subscribe({
channel: 'my_channel',
callback: function(data) {
chat(data);
}
});
pubnub.publish({
channel: 'my_channel',
message: data
});
The pubnub variable was out scope for the unsubscribe.
Developer had to declare pubnub outside the function to unsubscribe.