Reputation: 219
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...
Upvotes: 2
Views: 4159
Reputation: 1287
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');
}
Upvotes: 0
Reputation: 219
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';
Upvotes: 4