How do flutter client socket connect to socket server? - javascript

I want to connect my socket server through flutter mobile application, but it's not working.
My server code (Node.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("biri geldşi")
socket.on('chat message', function(msg){
console.log(msg)
io.emit('chat message', msg);
});
});
http.listen(port, function(){
console.log('listening on *:' + port);
});
My Flutter application code:
import 'package:socket_io_client/socket_io_client.dart' as IO;
main() {
IO.Socket socket = IO.io('http://192.168.1.102:3000');
socket.on('connection', (_) {
print('connect');
socket.emit('chat message', 'test');
});
socket.on('event', (data) => print(data));
socket.on('disconnect', (_) => print('disconnect'));
socket.on('fromServer', (_) => print(_));
}

Related

socket io load failed

Hi I am quite new to socket io, and I am trying to make a simple chat. The problem is that I keep on getting errors for failed loading. I can't figure it out what is wrong with my code. I am using the code from: https://socket.io/get-started/chat/
<ul id="messages"></ul>
<form id="form" action="">
<input id="input" autocomplete="off" /><button>Send</button>
</form>
<script src="https://cdn.socket.io/3.0.0/socket.io.js"><script/></script>
<script>
var socket = io("http://192.168.88.152:3000");
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>
The code for backent:
const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);
app.get('/', (req, res) => {
res.sendFile(__dirname + '/chat.html.php');
});
io.on('connection', (socket) => {
console.log('a user connected');
});
io.on('connection', (socket) => {
console.log('a user connected');
socket.on('disconnect', () => {
console.log('user disconnected');
});
});
io.on('connection', (socket) => {
socket.on('chat message', (msg) => {
console.log('message: ' + msg);
});
});
io.on('connection', (socket) => {
socket.on('chat message', (msg) => {
io.emit('chat message', msg);
});
});
server.listen(3000, () => {
console.log('listening on *:3000');
});
In this link It hasn't serve static file in socket.io example. So you can fix this error by using script as cdn:
<script src="https://cdn.socket.io/3.0.0/socket.io.js"><script/>
or download cdn file and serve it your file with express: link

Having Trouble Running my Server.JS. Listening Error

Hello I am having trouble starting up my server.js. Every time that I would run node towards it. It wills always show this error "listening on *:3000". Here is my code for my server.js.
var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
app.get('/chat', (req, res) => {
res.sendFile(__dirname + '/chat.html');
});
io.on('connection', (socket) => {
console.log('User Online');
socket.on('codeboard-message', (msg) => {
console.log('message: ' + msg);
socket.broadcast.emit('message-from-others', msg);
});
});
var server_port = process.env.YOUR_PORT || process.env.PORT || 3000;
http.listen(server_port, () => {
console.log('listening on *:' + server_port);
});
Do I have to use a different port or am I missing a line of code for this server to work? Any help will be appreciated!
var app = require('express')();
var http = require('http').createServer(app);
var server_port = process.env.PORT || 3000;
http.listen(server_port, () => {
console.log('listening on *:' + server_port);
});
try only this without socket io. If it works, add socket io code

Initialize Socket.IO from server instance in another module

I want to initialize my socket inside a route and according to documents I have to pass server instance to my socket. I have a separate server.js file like this:
var app = require('./app');
var http = require('http');
var port = '2002';
app.set('port', port);
var server = http.createServer(app);
server.listen(port, function(err){
if(err)
console.log(err);
else
console.log('Server listening on port : ' + port);
});
module.exports = server;
and my router:
var express = require('express');
var server = require('../server');
var router = express.Router();
var io = require('socket.io')(server);
router.get('/', function(req, res, next){
res.render('index');
});
router.post('/', function(req, res, next){
io.on('connection', function(socket){
socket.emit('server emit', { hello: 'server emit' });
socket.on('client emit', function (data) {
console.log("Server received : " + data);
});
});
});
module.exports = router;
and my client script:
var socket = io('http://localhost:2002');
socket.on('connect', function() {
socket.on('server emit', function(data) {
console.log('inside eventtt');
console.log(data);
});
});
But I face this error in my browser console:
socket.io-1.4.5.js:1 GET http://localhost:2002/socket.io/?EIO=3&transport=polling&t=LPajDxI
I think the problem is due to wrong initialization of my socket on the server side, but I don't know how to handle the problem.

How to emit message using socket.io from two different files?

I am working with socket.io , so i created server on app.js and connect socket to client and i see emit('message') is printing to the client console, Now i want to send another message from different file consumer.js and emit message to client but its throwing exception on server side io.on is not a function. Any idea what is implemented wrong in consumer.js file ?
app.js
var express = require('express');
var app = express();
var consumer = require('./consumer');
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.emit('message', ' hello from server');
});
server.listen(3000, function () {
console.log('Example app listening on port 3000!');
consumer.start();
});
consumer.js
var io = require('socket.io');
function startConsumer(consumer) {
consumer.on('message', function (message) {
logger.log('info', message.value);
io.on('connection', function(client) {
console.log('Consumer connected...');
client.emit('Consumer-Message', 'Message from dit consumer');
});
});
consumer.on('error', function (err) {
console.log('error', err);
});
};
exports.start = start;
angularCtrl.js
socket.on('message',function (data) {
console.log(data);
});
socket.on('Consumer-Message',function (data) {
console.log(data);
});

Maintaining Namespaces in an Array doesn't work

i'm making a chat application divided by several namespaces, in other words i want to divide interests, some of them like to talk 'dogs' other wants to talk about 'cats' and so on...
This is my first version, in which i stored each namespace in a variable(it works perfectly) :
Server side:
var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
app.get('/default', function(req, res){
res.sendfile('index1.html');
});
app.get('/dog', function(req, res){
res.sendfile('index2.html');
});
app.get('/', function(req, res){
res.sendfile('index.html');
});
var cns1 = io.of('/default');
//default nsp
cns1.on('connection', function(socket){
socket.on('chat message', function(msg){
cns1.emit('chat message', msg);
});
});
var cns2 = io.of('/dog');
//dog nsp
cns2.on('connection', function(socket){
socket.on('chat message', function(msg){
cns2.emit('chat message', msg);
});
});
var cnsindex = io.of('/');
//index nsp
cnsindex.on('connection', function(socket){
socket.on('chat message', function(msg){
cnsindex.emit('chat message', msg);
});
});
http.listen(3000,function(){
console.log('listening on *:3000');
});
index*.html
<script>
//on index.html
var socket = io.connect('http://localhost:3000/');
//on index2.html
//var socket = io.connect('http://localhost:3000/dog');
//on index1.html
//var socket = io.connect('http://localhost:3000/default');
$(function(){
$('#bb').click(function (){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
});
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
});
</script>
Each namespaces keeps their messages private.
Now, when i wanted to store all Workspaces in an array to avoid repeating events, like that:
var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
app.get('/default', function(req, res){
res.sendfile('index1.html');
});
app.get('/dog', function(req, res){
res.sendfile('index2.html');
});
app.get('/', function(req, res){
res.sendfile('index.html');
});
var nss = [
io.of('/default'),
io.of('/dog'),
io.of('/')
];
for (i in nss)
{
nss[i].on('connection', function(socket){
socket.on('chat message', function(msg){
nss[i].emit('chat message', msg);
});
});
}
http.listen(3000,function(){
console.log('listening on *:3000');
});
In the second version doesn't receive messages for /dog and /default urls, and it allow sending messages from /dog and /default to /.
I'm stuck here, helps please!
Solved, this is a problem of closure thx to #levi :
for (i in namespaces)
{
namespaces[i].on('connection',handleConnection(namespaces[i]));
function handleConnection(ns)
{
return function (socket){
socket.on('chat message', function(msg){
ns.emit('chat message', msg);
});
}
}
}
Now my code works :)

Categories

Resources