Socket.io仅为一个客户端创建大量连接

时间:2019-03-19 05:35:54

标签: node.js react-native socket.io

我创建了一个react native应用程序,其中我只是从客户端创建一个连接,而服务器端则在不断创建新连接。我也不能从双方发出事件。我在客户端使用 socket.io-client 。因为我无法发布图像,但是正如您在服务器端代码中所看到的那样,我使用 counter ++ ,这样我就可以控制我的连接,并且连接不断增加,并且我只能连接一台设备。 这是我的本机代码。

componentDidMount = () => {
const socket = io('http://192.168.8.78:3000');
socket.on('connect', () => {
  console.log('connected...');
});
//console.log(socket.id);
console.log('emit00');
this.getUserLocationHandler();

navigator.geolocation.getCurrentPosition(position => {
  this.props.onAddUserLocation(position);
  //socket.emit('startingLocation', {position: position});

  this.setState(
    {

      startingLocation: {
        latitude: position.coords.latitude,
        longitude: position.coords.longitude,
        longitudeDelta: 0.0421,
        latitudeDelta: 0.0622
      }

    },
    err => console.log("err")
  );
});

this.watchId = navigator.geolocation.watchPosition(
  (position) => {
    // here we have to emit socket information and send position as data and when recieving it on backend save that position in an array by pushing it 
    //this.state.steps.push({latitude: position.coords.latitude, longitude: position.coords.longitude, longitudeDelta: 0.0421,
      //latitudeDelta: 0.0622});

    socket.emit('poistionChange',  position);
    socket.on('steps', (data) => {
      data.map(coord => {
        console.log(coord.coords);
        this.state.steps.push(coord.coords);
      })
    });

    this.props.onAddUserLocation(position)
  },
  (error) => this.setState({ error: error.message }),
  { enableHighAccuracy: true, timeout: 20000, maximumAge: 1000, distanceFilter: 1},
);

和下面是我的node.js代码...

    const express = require('express');
const app = express();
const server = require('http').createServer(app);
const io = require('socket.io').listen(server);

app.get('/', (req, res) => {
  res.send('Hello World');
})

const steps = [];
const startingPosition = {};
let counter = 0;

io.on("connection", (socket) => {
  console.log(counter++);

  socket.on('startingLocation', (data) => {
    console.log('starting')
    startingLocation = data;

  })
  socket.emit('steps', steps)
  socket.on('poistionChange', (data) => {
    console.log('position change');
    steps.push(data);


  })
});

server.listen(3000, () => console.log("listening..."));

0 个答案:

没有答案