3

socket简述

socket(双工协议)
网络中的两个程序,通过一个双向的连接来实现数据的交换,我们把连接的一端称为socket

图片描述

socket特性

自带连接保持

可以实现双向通信

socket分类

基于TCP的socket

基于UDP的socket

基于RawIP的socket

基于链路层的socket

socket实战

socketClient.js

var net = require('net');
var hostname = '127.0.0.1';
var port = 9000;

var client = new net.Socket();
client.setEncoding('utf-8');

// 与服务端建立连接
client.connect(port,hostname,function() {
    client.write('你好啊');
})

client.on('data',function(data) {
    // console.log(data);
    say()

})

// 逐行读取
const readline = require('readline');
// 建立通信标准
var r1 = readline.createInterface({
    input:process.stdin, //input标准
    output:process.stdout //out 标准
})

function say(){
    r1.question('请输入:',function(inputStr) {
        if(inputStr === 'bye') {
            client.destroy()
            console.log('客户端的socket退出')
        } else {
            client.write(inputStr + '\n')
        }
    })
}

socketServer.js

var net = require('net');
var clientServer = net.createServer();
var clientMap = new Object;

// 加一个标识
var i = 0;

// 接收客户端的连接
clientServer.on('connection',function(client) {
    console.log('亲 客户端发送过来一条信息');
    client.name = i++;
    clientMap[client.name] = client;
    client.on("data",function(data) {
        console.log(`客户端传来${data}`)
        client.write('服务端发送再见')
        broadcast(data,client)
    })
})

function broadcast(data,client){
    for (key in clientMap) {
        clientMap[key].write(client.name+"说:"+data)
    }
}


clientServer.listen(9000);

websocketClient.js

var ws = new WebSocket('ws://127.0.0.1:3000');

// 初始化
ws.onopen = function(){
    ws.send('你好哇')
}

ws.onmessage = function(event) {
    var chatRoom = document.getElementById('chatRoom');
    chatRoom.innerHTML += '<br />' + event.data;
}

websocketServer.js

var WebsocketServer = require('ws').Server;

var wss = new WebsocketServer({
    port: 3000
})

var clientMap = new Object;
var i = 0;
wss.on('connection',function(client) {
    console.log('亲,服务端发送过来一条信息');
    client.on('message',function(data) {
        client.name = i++;
        clientMap[client.name] = client;
        broadcast(data,client)
    })
})

function broadcast(data,client) {
    for (key in clientMap) {
        clientMap[key].send(client.name+'说:'+data)
    }
}

文章持续更新中~~~~


前端森林
2.4k 声望13.2k 粉丝