Socket and node.js send

Socket and node.js send

本文关键字:send js node and Socket      更新时间:2023-09-26

我正在尝试使用socket.io和node.js更新谷歌地图上的位置我有两种不同的方式来更新地图。可能是一些基本问题,因为我是新手。

1) 使用API调用,其工作方式如下:

app.post('/location',函数(请求,响应){

var obj = request.body;
//var obj = { gps_latitude: '59.33535', gps_heading: '0.0', gps_timestamp: '1397132411524', gps_speed: '0.0', device_id: 'oscar', gps_longitude: '17.999672099999998' };
//insertLocation(obj);
console.log("Connected clients: " + map_clients.length);
for(var i=0; i < map_clients.length; i++){
  var client = map_clients[i];
  var jsonString = JSON.stringify({ type:'gps', data:obj});
  console.log(jsonString);
  client.send(jsonString);
}
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("OK");
response.end();
});

2) 从客户端使用套接字更新这不起作用吗?服务器代码看起来像:

io.sockets.on("connection", function(client){ 
map_clients.push(client);
//Update position  
client.on('position', function (data) {
    var obj = { gps_latitude: '59.33535', gps_heading: '0.0', gps_timestamp: '1397132411524', gps_speed: '0.0', device_id: 'oscar', gps_longitude: '17.999672099999998' };
    var jsonString = JSON.stringify({ type:'gps', data:obj});
    console.log(jsonString);
    client.send(jsonString);         
});
client.on('disconnect', function(){
map_clients.splice(map_clients.indexOf(client), 1);
})
});

我可以看到它在控制台中发送数据:

debug-websocket写入3:::{"type":"gps","data":{

但是地图没有更新。在地图客户端,我有这个代码,但当我尝试通过上面的套接字代码进行tpo更新时,它从未被触发。

socket = io.connect(socket_url);
  socket.on('message', function(d){
    console.log("update position");
    var parsedObj = JSON.parse(d);
    if(parsedObj.type === 'gps'){
      var gps = parsedObj.data;
      $('#messages').append(formatGPSHTMLOutput(gps));
      processGPS(gps);
    }
  });

您应该使用

client.emit('position', {your:"jsondata"})

而不是client.send,如果您使用

client.on('position', callback)

在服务器端,您还需要使用

socket.on('position', callback) 

在客户端