簡體   English   中英

使用Socket.io作為服務器和客戶端

[英]Using Socket.io to be the server and the client

如何使具有套接字連接到一個客戶端(客戶端A)的服務器也具有套接字連接到另一台服務器? 基本上,我如何使服務器也成為客戶端(連接到另一台服務器)?

如果答案是加載socket.io-client,那我該如何在javascript文件中這樣做呢?

var app = require('express')();
var http = require('http').Server(app);
var http2 = require('http').Server(app);

var io = require('socket.io')(http);

app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(socket){
    console.log("asdf");
  socket.on('chat message', function(msg){
    io.emit('chat message', msg);
  });
});

http.listen(3050, function(){
  console.log('listening on *:3050');
});


http2.listen(1337, function(){
  console.log('listening on *:1330');
});



var socket = require('socket.io-client')('http://localhost:1337');
socket.on('connect', function(){

  console.log('connected');
});

我假設您的意思是因為您提到javascript文件,所以希望將節點服務器作為客戶端運行。 這是在節點中設置套接字客戶端的方法。 獲取軟件包npm i socket.io-client 然后在節點中使用它,如下所示。

var socket = require('socket.io-client')('http://localhost:1337');
socket.on('connect', function(){
  console.log('connected')
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM