I am writing a chat application without explicit server side web socket.
I am using RabbitMQ webstomp as the web socket container and plain Javascript as the cleint to both send and receive data.
Below is the flow :
Browser -> native websocket/sockjs -> rabbitmq /sockjs websocket (ws://127.0.0.1:15674/ws or http://localhost:15674/stomp) -> put messages to queue.
However while testing the application, I am not able to send the data directly to ws://127.0.0.1:15674/ws. I am just able to connect to it.
I use the below template to send and receive data on client Javascript.
ws = new WebSocket('ws://127.0.0.1:15674/ws');
client = Stomp.over(ws);
client.connect('guest','guest',on_connection,on_connect_error,'/');
client.send(queue, {'reply-to':'/temp-queue/logs',priority: 9}, "msg" );
client.onreceive = func()
The problem,most likely,in your code is:
client.send(queue, {'reply-to':'/temp-queue/logs',priority: 9}, "msg" );
you have to send the message to a topic
I suggest to see the example here: https://github.com/rabbitmq/rabbitmq-web-stomp-examples
Here is a rapid example i made starting for the original example:
var client = Stomp.client('ws://localhost:15674/ws');
client.debug = pipe('#second');
var print_first = pipe('#first', function(data) {
client.send('/topic/test', {"content-type":"text/plain"}, data);
});
var on_connect = function(x) {
id = client.subscribe("/topic/test", function(d) {
print_first(d.body);
});
};
var on_error = function() {
console.log('error');
};
client.connect('guest', 'guest', on_connect, on_error, '/');
Related
c# winform tries to send node.js socket through socket.
The client is connected to server, but the socket.emit value and socket.on value do not communicate normally.
I'd like to find a solution to this.
I would like to send this name of client to the server as json type data, receive json type data from the server, read it, and send data back to json.
The data of socket.emit and socket.on are not working properly, so the code has been deleted.
c# code
private void socketLogin(string email, string pw)
{
var socket = IO.Socket("http://localhost:3000/login.html");
socket.On(Socket.EVENT_CONNECT, () =>
{
});
var loginjson = new JObject();
loginjson.Add("email", email);
loginjson.Add("password", pw);
socket.Emit("socketlogin", loginjson.ToString());
socket.On("login", (data) => {
MessageBox.Show(data.ToString());
});
}
node.js Code
var server = require('http').Server(app);
var io = require('socket.io')(server);
io.on('connection', function(socket) {
console.log('connection');
socket.on('socketlogin', function(data) {
var testLogin = { 'Login': "success" };
socket.emit('login', data);
});
});
server.listen(app.get('3000'))
in your C# you are making your socket inside a function, but at the end of the function the socket is thrown away because it is only a local variable.
There are many ways to deal with this, but essentially what you want to do is use a thread to handle the socket comms then dispatch things back to your UI thread.
I am trying to send a string to the client like this:
socket.emit("start", "calm");
but it is throwing an error, is it because it is not an object ?
First thing first, you should make sure your socket between server-side and client-side is connect. And register event and function to the socket.
Server-side
io.sockets.on('connection', function(socket) {
console.log('socket connect' + socket.id);
// when a client connect to server within socket, server will send hello
io.emit('newMsg', "hello")
socket.on('disconnect', function() {
console.log('socket disconnect');
})
// when server receive a message, it will send to all client which connect
to the server
socket.on('data', function (data) {
console.log(socket.id +': ' + data.msg);
var message = {from: socket.id,
msg: data.msg
}
io.emit('newMsg', message)
})
}
Client-side
var socket = io('http://localhost:3000');
socket.on('connect', function (data) {
console.log(data)
})
socket.on('newMsg', function(data) {
console.log(data)
})
// function could bind on button on client side page, get input and send data
function sendData() {
var input = document.getElementsByTagName('input')
var text = input[0].value
var data = { msg: text }
socket.emit('data', data)
}
open console, the information would show in the console. When sending a message on server-side, could use 'broadcast' instead of 'emit' as well to send the message to other clients except you. Read the doc: socket.io doc
Here is my code:
var socket = require('socket.io-client')('http://127.0.0.1:3000/printers', {
query: "shop=" + "123456",
transports: ["websocket"]
});
If I delete query, I can connect to socket. Where am I wrong?
There doesn't seem to be anything wrong with your client-side code. I can connect by copying and pasting your code.
I suspect the problem is within your server-side code. Here is an example I am using with your client-side code:
var http = require('http');
var io = require('socket.io');
var server = http.createServer(function(req,res){
res.writeHead(200);
res.end('Hello, World!\n');
});
server.listen(80);
var socket = io.listen(server);
socket.use(function(socket, next){
console.log("Query: ", socket.handshake.query);
if (socket.handshake.query.shop == '123456') {
next();
}
next(new Error('You cannot use that shop'));
});
socket.on('connection', function(client) {
console.log('New Connection');
});
I'm able to obtain the query data in the 'socket.use' function. If I don't call the next() function, the client will never get the message that the server has received the response and is connected.
I recommend checking out the example used in this thread.
server.js
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
app.use(express.static(__dirname + '/public'));
io.on('connection', function(client) {
console.log('Client connected...');
client.on('join', function(data) {
console.log(data);
io.emit('messages', 'Hello');
});
});
index.html
<script>
var socket = io.connect('http://localhost:7777');
socket.on('connect', function(data) {
socket.emit('join', 'Hello World from client');
});
socket.on('messages', function(data) {
alert(data);
});
</script>
I tried to implement very basic of Socket.io.
However, data sending from client to server is available but from server to client doesn't work.
In the command running server.js, 'Hello World from client' is printed. However, alert window doesn't work in the web browser.(I've also tried to console.log).
How to solve this?
Editted
I've put server.js codes in the app.get('/', function(req, res)){ ... }
Then, it doesn't work. Why it doesn't work in app.get?
Try this, I hope it works:
io.on('connection', function(client) {
console.log('Client connected...');
client.on('join', function(data) {
console.log(data);
io.emit('join', data); //this code sending data from server to client
});
});
If you're just trying to fetch some data with an Ajax call such as /test, then there is no need to use socket.io. That's just a classic request/response.
app.get('/test', function(req, res) {
// collect your data and then send it as a response
res.json(data);
});
If you're just trying to incorporate data into a web page that is requested, then you can use res.render() with the template engine of your choice (ejs, handlebars, pug, etc...). That would typically look like this:
app.get('/test', function(req, res) {
// collect your data and then pass it to res.render() to render your
// your template using that data
res.render('someTemplateName', data);
});
The main thing that socket.io is useful for is "pushing" data from server to client without a client request. So, if something happened on the server that the client was not aware of and the server wanted to tell the client about it, then socket.io would be used for that. The classic example is a chat app. Person A sends a chat message to the server that is addressed to Person B. The server receives that message and then needs to "push" it to Person B. That would be perfect for an already connected socket.io connection because the server can just push the data directly to the Person B client, something the server can't do with request/response (since there is no request from person B).
If you still think you need socket.io, then please describe exactly what you're trying to do with it (step by step what you're trying to send to the client).
socket.on("message",function (reply_data) {
console.log('inside on message functions ')
console.log(reply_data);
})
please change 'messages' to "message" that worked for me
I'm trying to use React Native's built in Websocket support. I have this code:
var hostname = "192.168.X.XXX";
var port = "4567";
const webSocket = new WebSocket("ws://" + hostname + ":" + port + "/chat");
and I have this:
componentWillMount: function(){
console.log("MOUNTING CHAT COMPONENT");
webSocket.onopen = function(){
console.log("binding to chat room");
bindToChatRoom();
setTimeout(keepWebSocketOpen, 30000);
ws_connected = true;
};
webSocket.onmessage = function (msg) {
this.handleMsg(msg);
};
webSocket.onclose = function () {
console.log("WebSocket connection closed");
ws_connected = false;
};
webSocket.onerror = function (e){
//add some error handling -> DO THIS
console.log(e.message);
};
},
I'm running a local server using sparkjava, with this:
webSocket("/chat", ChatWebSocketHandler.class);
etc. I've tested the server, and I can connect to it (and send messages) both through both my web browser on my laptop AND on my phone with URL 192.168.x.xxx:4567/chat . However, when I run the react native app, I never see the console message "binding to chat room". Am I missing something? How come this websocket never opens?
Just want to note, I also tried connecting here:
ws://echo.websocket.org
which is described here:
http://www.websocket.org/echo.html
This is a known working websocket, so I know it's purely a react native issue...
Turns out that I had the line of code
const webSocket = new WebSocket("ws://echo.websocket.org");
in the wrong place. If you move it into componentWillMount, it works just fine.