套接字不能用于使用ws的React native和Node.js服务器
我正尝试使用套接字将我的后端(node.js服务器)连接到前端(反应原生应用程序)。 但问题是代码永远不会进入io.on('连接',…)。 即套接字连接没有build立。
任何帮助表示赞赏。
这是客户端代码:
import React, { Component } from 'react'; import { Alert, Button, Text, View } from 'react-native'; export default class App extends Component { constructor(props) { super(props); const ws = new WebSocket('ws://localhost:3000'); console.log("This is client side Web socket.") ws.onopen = () => { console.log("Its connected") ws.send('something'); // send a message }; } }
这是服务器端的代码:
var app = require('express')(); var http = require('http').Server(app); var io = require('socket.io')(http); io.on('connection', function(socket){ console.log('a user connected'); }); http.listen(3000, function(){ console.log('listening on *:3000'); });
安装npm模块socket.io-client
然后尝试
import React, { Component } from 'react'; import { Alert, Button, Text, View } from 'react-native'; import SocketIOClient from 'socket.io-client'; export default class App extends Component { constructor(props) { super(props); var ws = SocketIOClient('ws://localhost:3000'); // replace localhost with ip ws.on('connect', function() { console.log("hello"); }); } }