首页 > 解决方案 > 带有 Socket.io 问题的实时天才聊天

问题描述

我正在尝试使用 socket.io 以实时方式实现 Gifted Chat,但我遇到了问题。我能够让 socket.io 连接,发出消息,但是当我有一个运行应用程序的 android 模拟器和 iPhone 模拟器时,它没有实时显示。

服务器.js

const express = require("express");
const http = require("http");
const app = express();
const server = http.createServer(app);
// Attempt at Socket.io implementation
const socket = require('socket.io')
const io = socket(server)

const bodyParser = require('body-parser');
const Message = require("./models/message");
const SportsMessage = require('./models/sportsMessage')
const GamerMessage = require('./models/gamerMessage')
const mongoose = require('mongoose');

// MongoDB connection
mongoose.connect(
  'mongodb+srv://yada:yada@cluster0.kt5oq.mongodb.net/Chatty?retryWrites=true&w=majority', {
    useNewUrlParser: true,
    useUnifiedTopology: true
  }).then(() => {
    console.log('Connected to the database!')
  }).catch(() => {
    console.log('Connection failed oh noooooo!')
});

// Parse the request body as JSON
app.use(bodyParser.json());

// GET messages, don't change these bro
app.get("/api/messages", (req, res) => {
  Message.find({}).exec((err, messages) => {
    if(err) {
       res.send(err).status(500);
    } else {
       res.send(messages).status(200);
    }
  });
});

app.get("/api/sportsMessages", (req, res) => {
  SportsMessage.find({}).exec((err, messages) => {
    if(err) {
       res.send(err).status(500);
    } else {
       res.send(messages).status(200);
    }
  });
});

app.get("/api/gamerMessages", (req, res) => {
  GamerMessage.find({}).exec((err, messages) => {
    if(err) {
       res.send(err).status(500);
    } else {
       res.send(messages).status(200);
    }
  });
});

// POST messages
app.post('/api/messages', (req, res) => {
  Message.create(req.body).then((message) => {
      res.send(message).status(200);
  }).catch((err) => {
      console.log(err);
      res.send(err).status(500);
  });
});

app.post('/api/sportsMessages', (req, res) => {
  SportsMessage.create(req.body).then((message) => {
      res.send(message).status(200);
  }).catch((err) => {
      console.log(err);
      res.send(err).status(500);
  });
});

app.post('/api/gamerMessages', (req, res) => {
  GamerMessage.create(req.body).then((message) => {
      res.send(message).status(200);
  }).catch((err) => {
      console.log(err);
      res.send(err).status(500);
  });
});

// Socket.io connection
io.on('connection', socket => {
  socket.emit('your id', socket.id)
  socket.on('send message', body => {
      console.log(body)
      io.emit('send message', body)
  })
  console.log("connected to dat socket boiii")
})

server.listen(8000, () => console.log("server is running on port 8000"));

聊天画面

import React, { useState, useEffect, useContext, useRef } from 'react'
import { View, Text, Button, StyleSheet } from 'react-native'

import io from 'socket.io-client'

import useMessages from '../hooks/useMessages'
import { Context as UserContext } from '../context/UserContext'

import { GiftedChat as GChat } from 'react-native-gifted-chat'

const GeneralChat = () => {
  const [messages, ids, getMessages, randomId, setMessages] = useMessages()
  const { state: { username } } = useContext(UserContext)

  const socketRef = useRef()
  socketRef.current = io('{MyIP}')

  useEffect(() => {
    getMessages()
    randomId()
    const socket = io('{MyIP}')
    socket.on('your id', id => {
      console.log(id)
    })
  }, [])

  const onSend = (message) => {
    let userObject = message[0].user
    let txt = message[0].text
    console.log(message)
    setMessages(previousMessages => GChat.append(previousMessages, message))
    const messageObject = {
      text: txt,
      user: userObject
    }
    socketRef.current.emit('send message', messageObject)
    fetch("{MyIP}/api/messages", {
      method: "POST",
      headers: {
          "Content-Type": "application/json"
      },
      body: JSON.stringify(messageObject)
      }).then((res) => {
          return res.json();
      }).catch((err) => {
          console.log(err);
      });
  }

  return (
    <GChat
      // isLoadingEarlier
      scrollToBottom
      infiniteScroll
      loadEarlier
      alwaysShowSend
      renderUsernameOnMessage
      inverted={true}
      showUserAvatar
      messages={messages}
      onSend={message => onSend(message)}
      user={{
        _id: ids,
        name: username,
        avatar: 'https://placeimg.com/140/140/any'
      }}
    />
  )
}

GeneralChat.navigationOptions = () => {
  return {
    title: 'General Chat',
  }
}

const styles = StyleSheet.create({

})

export default GeneralChat

标签: mongodbreact-nativesocketssocket.ioreact-native-gifted-chat

解决方案


推荐阅读