[英]react-native socket.io emit / on doesn't work
大家好,我正在與 RN 學習一個簡單的聊天應用程序
我在服務器代碼中檢查了與連接事件的連接服務器也可以獲取我的套接字的 ID
但是, Any Emit 或 On 不起作用。
這是我的服務器代碼
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);
});
這是客戶端代碼
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>
);
}
}
使用此代碼,當我按下 Button 時,我認為 socket.on 在服務器中有效
同樣,當套接字在服務器中連接時,客戶端會更改渲染中的文本。
但兩者都不起作用。
請幫我...
我發現問題.....
Socket.io 已更新,因此我需要更換
import io from 'socket.io-client'
到
import io from 'socket.io-client/dist/socket.io';
首先轉到你的項目根目錄並安裝
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');
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.