Reputation: 121
I am trying to connect my backend(node.js server) to frontend (react native app) using sockets. But the problem is the code never goes into io.on('connection', ...). i.e. socket connection is not being established.
Any help is appreciated.
This is client-side code:
import React, { Component } from 'react';
import {
Alert,
Button,
Text,
View
} from 'react-native';
export default class App extends Component {
constructor(props) {
super(props);
const ws = new WebSocket('ws://localhost:3000');
console.log("This is client side Web socket.")
ws.onopen = () => {
console.log("Its connected")
ws.send('something'); // send a message
};
}
}
This is server-side code:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
io.on('connection', function(socket){
console.log('a user connected');
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
Upvotes: 1
Views: 618
Reputation: 740
install npm module socket.io-client
then try
import React, {
Component
} from 'react';
import {
Alert,
Button,
Text,
View
} from 'react-native';
import SocketIOClient from 'socket.io-client';
export default class App extends Component {
constructor(props) {
super(props);
var ws = SocketIOClient('ws://localhost:3000'); // replace localhost with ip
ws.on('connect', function() {
console.log("hello");
});
}
}
Upvotes: 1