简体   繁体   中英

react-native socket.io emit / on doesn't work

Hello guys I studying a simple chat app with RN

I checked connection with connection event at Server code Also server can get my socket's id

But, Any Emit or On doesn't work.

Here's my server Code

var http = require('http');
var express = require('express'),
app = module.exports.app = express();
console.log("serverStarted");
var server = http.createServer(app);
const io = require('socket.io')(server);
server.listen(3000);  //listen on port 80
io.on('connection',function(socket){
    console.log("Client Connected."+socket.id);
    socket.on('Button',function(data){
        console.log("ButtonPressed");
    });
    socket.emit('userid',socket.id);
});

And this is Client side code

import React, { Component } from 'react';
import {
  Button,
  Alert,
  Platform,
  StyleSheet,
  Text,
  View
} from 'react-native';
import SocketIOClient from 'socket.io-client';

let socket;
type Props = {};
export default class App extends Component<Props> {
    constructor(){
    super();
    socket = SocketIOClient('http://myip:3000');
    Alert.alert("Socket is Connected.");
    socket.on('userid',(id)=>{
      this.setState({userid:{id}});
      Alert.alert(id);
    })
  }

  state = {
    userid:"id"
  }
  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
          Welcome to React Native!
        </Text>
        <Button title = "pres" onPress={()=>{
    socket.emit('Button',"button");
    }}>
          </Button>
        <Text style={styles.instructions}>
          {this.state.userid}
        </Text>
        <Text style={styles.instructions}>
          {instructions}
        </Text>
      </View>
    );
  }
}

With this code, When I press Button I think that the socket.on Works in Server

Also when socket is connected in server, the client change the Text in Render.

But both doesn't work.

Please help me...

I Found Problem.....

The Socket.io is updated so I need to replace

import io from 'socket.io-client' 

to

import io from 'socket.io-client/dist/socket.io';

First of all goto you project root directory and install

npm i socket.io-client

import SocketIOClient from 'socket.io-client';


constructor(props) {

    super(props);

    //use your own local ip
     this.socket = SocketIOClient('http://localhost:9000/');

     this.socket.on('response', (messages) => {
      Alert.alert("response." + JSON.stringify(messages));
      console.log("response" + JSON.stringify(messages));
    });
  }
  componentDidMount(){
      this.socket.emit('Request_name', '1');
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM