Wednesday 26 April 2017

React Native - creating web-socket connection issue

I am trying to create a web-socket connection between React-Native app and a server. When I print the object of ws on console, I am getting an readystate corresponding to 3, which means it's in closed state. What should I do to make it work? When I am giving the path to ws on client side as 'wss://echo.websocket.org', It shows that it is in readystate 0, which means open and when I run server with another client, It works. I am confused as to what is happening.

I have used web-socket provided by React-Native.

These are my client and server side code

client side

/**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/

import React, { Component } from 'react';
import {
 AppRegistry,
 StyleSheet,
 Text,
 View
} from 'react-native';

export default class test2 extends Component {
 constructor(props){
  super(props);
  const ws = new WebSocket('ws://localhost:8080');
  console.log("This is client side Web socket.",ws)
  ws.onopen = () => {
   console.log("Its connected")
   ws.send('something'); // send a message
  };
 }

 render() {
  return (
   <View style={styles.container}>
     <Text style={styles.welcome}>
       Welcome to React Native!
     </Text>
     <Text style={styles.instructions}>
       To get started, edit index.android.js
     </Text>
     <Text style={styles.instructions}>
       Double tap R on your keyboard to reload,{'\n'}
       Shake or press menu button for dev menu
     </Text>
   </View>
  );
 }
}

const styles = StyleSheet.create({
 container: {
  flex: 1,
  justifyContent: 'center',
  alignItems: 'center',
  backgroundColor: '#F5FCFF',
 },
 welcome: {
  fontSize: 20,
  textAlign: 'center',
  margin: 10,
 },
 instructions: {
 textAlign: 'center',
 color: '#333333',
 marginBottom: 5,
 },
});

AppRegistry.registerComponent('test2', () => test2);

Server.js

var Server = require('ws').Server;
var port = process.env.PORT || 8080;
var ws = new Server({port: port});
console.log("This is server web socket ",ws)

ws.on('connection', function(w){  
 console.log("New connection opened");
   w.on('message', function(msg){
    console.log('message from client',msg);
  });

w.on('close', function() {
  console.log('closing connection');
 });

});

Thanks.



via Chinmay H

No comments:

Post a Comment