mongodb - 带有 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
解决方案
推荐阅读
- javascript - 如何在Vuejs中设置登录页面的用户名和密码?
- c++ - 无法在 Visual Studio 调试器中编辑 std::atomic 值
- python - 如何在 vs 代码中激活虚拟环境?
- java - 如何在 PostGIS 中的两点(A 点和 B 点)之间获取点(纬度和经度)?
- javascript - 匹配 navigator.userAgent 中的特定字符串并从对象数组中获取详细信息
- java - 如果我在使用 Ehcache 时没有在 XML 中定义缓存会发生什么?
- php - 尝试使用 pluck 方法在选择中显示数据 - Laravel
- cytoscape.js - Cytoscape.js 将多个边缘组合成一个(更厚的)边缘
- outlook - 如何区分图 API 中发送和接收的消息?
- node.js - 是否可以将环境变量从 Elastic Beanstalk 控制台传递到 React 应用程序?