Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
622 views
in Technique[技术] by (71.8m points)

socket.io - how the client can get a copy of the client API

I've been doing some reading and it seems like when you implement a socket.io server, the server can provide the required client side files.

Example of a nodejs application: (it's verbose on purpose... so I can learn)

const express = require('express');
const app = express();
const socketio = require('socket.io');
app.use (express.static(__dirname + '/public'));
const expressServer = app.listen(9000);

const io = socketio(expressServer, {
    path: '/socket.io',
    serveClient: true,  
    transports: ['polling','websocket']
});

Client side code:

<!-- expose the socket.io client api -->
<script src='/socket.io/socket.io.js'></script>
<script>
    //invoke io / connect to the socket server running on localhost 9000.  Per the docs, it also creates a new "manager" at the same time:  https://socket.io/docs/v3/client-api/#io-url-options
    // any of the "options" you create with the connection, the manager takes care of. 
    const socket = io('http://localhost:9000'); 


    socket.on('msgFromServer',(dataFromServer)=>{
        console.log(dataFromServer);
        socket.emit('msgToServer',{data: "Client says: 'doodee'"}) //https://socket.io/docs/v3/client-api/#socket-emit-eventName-%E2%80%A6args-ack
    });
    
    //https://socket.io/docs/v3/client-api/#Event-%E2%80%98ping%E2%80%99
    socket.on('ping',()=>{
        console.log('Server just pinged');
    });
    socket.on('pong', (latency)=>{
        console.log(latency);
        console.log('Ponged the server');
    })
</script>

In this type of an example... where the client is a web application, I can see that the server , by virtue of the fact that we set "serveClient" to true, provides the client with the client side socketio API.

But how do you do this in a node to node example? Also ... I think the bigger question is why should I do this? Why is it better(?) to have the server provide clients with the API? One answer I can think of is that the server will provide a version of the API that compatible. aka to avoid version incompatibilities between the server and the client.

Am I understanding this correctly? any other use cases?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...