Project Structure
Problem
As you see above, I want to connect React-Native-App with React-Web Using websocket.
I succed to send data from React Native app to Server.js but fail to send data from Server.js to React Web Client(App.js).
Here is My React (Web) directory structure.
React (Web) Structure
/client
/node_modules
/public
/src
/App.js
package.json
server.js
package.json
And My Code.
Code
- App.js (React Web : ../client/src/App.js)
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
const WebSocket = require('ws');
class App extends Component {
componentDidMount() {
let ws = new WebSocket('ws://localhost:8080');
ws.on('message', function incoming(data) {
console.log(data);
});
}
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to React</h1>
</header>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
</div>
);
}
}
export default App;
- Server.js (React Web : ../Server.js)
/**
* WebSocket
*/
const express = require('express');
const http = require('http');
const WebSocket = require('ws');
const app = express();
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
//initialize a simple http server
const server = http.createServer(app);
//initialize the WebSocket server instance
const wss = new WebSocket.Server({ server });
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(data) {
// Broadcast to everyone else.
wss.clients.forEach(function each(client) {
console.log('client', client);
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(data);
}
});
console.log('received: %s', data);
ws.send(`Hello, you sent -> ${data}`);
});
ws.on('hello', function incoming(data) {
console.log('received: %s', data);
});
ws.send('Hi there, I am a WebSocket server');
});
//start our server
server.listen(process.env.PORT || 8080, () => {
console.log(`Server started on port ${server.address().port} :)`);
});
- App.js (React Native App)
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
open: false,
connected: false,
};
this.socket = new WebSocket('ws://127.0.0.1:8080');
this.socket.onopen = () => {
this.setState({connected:true})
};
this.testPusher = this.testPusher.bind(this);
}
testPusher() {
console.log('testPusher');
if( this.state.connected ) {
this.socket.send(JSON.stringify({
messgaes: 'hello~!~!~!',
}))
this.setState(prevState => ({ open: !prevState.open }))
}
}
// ...
}
How can I do this?
Please let me know, Thank you!
Is there another solution?
If there is, Please Recommend me!
Thanks for reading!