0

Client:

      import { StatusBar } from 'expo-status-bar';
  import React, { Component } from 'react';
  import { StyleSheet, Text, View, TextInput } from 'react-native';
  import io from "socket.io-client";
  class App extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        chatMessage: "",
        chatMessages: []
      };
  }
  componentDidMount() {
    console.log('componentDidMount');
    this.socket = io.connect("http://localhost:3000");
    
    console.log(this.socket);
    this.socket.on("chat message", msg => {
      
    console.log(msg);
          this.setState({ chatMessages: [...this.state.chatMessages, msg]   
      });
  });
  }

  submitChatMessage() {
    this.socket.emit('chat message', this.state.chatMessage);
    this.setState({chatMessage: ''});
  }
  render() {
    const chatMessages = this.state.chatMessages.map(chatMessage => (
      <Text style={{borderWidth: 2, top: 100, backgroundColor:'#e6e6e6'}}>{chatMessage}</Text>
    ));

    return (
      <View style={styles.container}>
        <TextInput
          style={{height: 40, borderWidth: 2, top: 10}}
          autoCorrect={false}
          value={this.state.chatMessage}
          onSubmitEditing={() => this.submitChatMessage()}
          onChangeText={chatMessage => {
            this.setState({chatMessage});
          }}
        />
        {chatMessages}
      </View>
  );
  }
  }

  const styles = StyleSheet.create({
    container: {
      height: 400,
      flex: 1,
      backgroundColor: '#F5FCFF',
    },
  });

  export default App;

Server:

        const express = require("express");
    const app = express();
    const server = require("http").createServer(app);
    const io = require("socket.io")(server);
    const port = 3000;

    io.on("connection", socket => {
        console.log("a user connected :D");
        socket.on("chat message", msg => {
        console.log(msg);
        io.send("chat message", msg);
        });
    });

    server.listen(port, () => console.log("server running on port:" + port));

Can anyone see where im going wrong?

i Aslo found this that socket.io does not work on Android?

https://stackoverflow.com/questions/37505661/react-native-with-socket-io-doesnt-work

1 Answer 1

1

this.socket = io.connect("http://localhost:3000");

You are trying to connect the socket in your mobile to a server on your mobile.

The localhost in your phone and in your computer are different.

Change the URL to the public id of your server.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.