socket通信

前端通信方式

基于net模块的socket
  • 服务器
    任务:接收数据,界面展示
    const net = require( 'net' )
    const server = new net.createServer()
    const port = 8000
    const hostname = '127.0.0.1'
    const clients = {}
    let count = 0
    
    server.on( 'connection', ( client ) => { //client就是我们连接的客户端
    	 client.name = ++count // 计数的思维
    	 clients[ client.name ] = client     // { 1: client}
    
    // 服务端接收客户端发来的信息,并且展示在服务终端界面上
    
    client.on( 'data', ( msg ) => { // msg也可能是发过来的二进制,如果是二进制,那么我们使用 toString()
     console.log( `客户端${ client.name }说:${ msg.toString() }` )
    
     // 数据展示
    	boardcast( client, msg )
      })
    
    // 处理异常的监听
    
    client.on( 'error' ,( e ) => {
    		 console.log( 'error is>' + e )
    })
    
    // 客户端的正常下线
    
    client.on( 'close', () => {
    	 	delete clients[ client.name ] // 删除下线的客户端
    		console.log( `客户端${ client.name }下线了` )
     })
    })
    server.listen( port,hostname,() => {
    	console.log( `The server is running at: http://${ hostname }:${ port }` )
    })
    
    function boardcast ( client, msg ) {
    	 for( var key in clients ){
    	  clients[ key ].write( `客户端${ client.name }说:${ msg }` )
     }
    }
    
  • 客户端
    任务:
    1. 创建一个socket,然后连接server( url ) net.Socket()
    2. 发送信息给服务器
    3. socket通信
      client可以进行数据的编写和发送
const net = require( 'net' )
const socket = new net.Socket()

const readline = require( 'readline' ) // 单行读取
const port = 8000
const hostname = '127.0.0.1'

const rl = readline.createInterface({ // 创建接口,进行信息的读写
  input: process.stdin,
  output: process.stdout
})

socket.connect( port,hostname, () => {
  // 上线提示信息
  socket.write( '您好~~~' )
})

socket.on( 'data', () => {
  say ()
})

// 监听客户端异常
socket.on(  'error', ( e ) => {
  console.log( 'error is>' + e )
})

// 客户端正常下线的提示

socket.on( 'close', () => {
  console.log( 'client is closed' )
})


function say () {
 rl.question( '请输入>', ( answer ) => {
  if( answer === 'bye' ){
    //下线了
    socket.destroy()
    rl.end()
  }else{
    socket.write( answer +'\n')
  }
 })
}

基于H5 webSocket

  • 目录如下
    目录
  • 通信主服务器,socketServer
/* 
通信的主服务器
*/

const WebSocket = require('ws')
const ws = new WebSocket.Server({
    port: 8080,
    host: '10.31.163.45'
})

let clients = {} //定义一个对象,保存客户端的数据
let clientName = 0 //计数
ws.on('connection', (client) => {

    // 客户端每传一个数据过来,触发事件,clientName自动加1,并且赋值给name属性
    client.name = ++clientName

    // 以键值对的形式保存客户端传来的数据,每个客户端都有独一的name属性
    clients[client.name] = client

    client.on('message', (msg) => {
        console.log(msg) //客户端接收到的信息
        broadcast(client, msg)
    })

    client.on('close', () => {
        delete clients[client.name]
        console.log(client.name + '离开了^_^')
    })
})


function broadcast(client, msg) {
    for (var key in clients) {
        clients[key].send(client.name + ' 说:' + msg)
    }
}
  • 客户端
//连接服务器

const wsport = 8080
const hostname = '10.31.163.45'
const ws = new WebSocket( `ws://${ hostname }:${ wsport } `)

ws.onopen = () => {
    ws.send( '欢迎您来到我的直播间')
}

//接收数据,将数据展示到界面上
ws.onmessage = ( msg ) => {
    const content = document.querySelector( '#content' )
    content.innerHTML += msg.data + '<br/>'
}

//异常报出
// ws.onerror = ( error ) =>{
//     console.log(error)
// }

ws.onclose = () => {
    console.log( 'closed' )
}

  • 创建静态服务器,用于展示界面
/* 
创建静态服务器,用于展示界面
*/

const express = require( 'express' )
const path = require('path')
const webport = 3000
const hostname = '10.31.163.45'
const app = express()

app.use( express.static( path.join( __dirname,'client')) )

app.listen( webport,hostname,() => {
    console.log(`The server is running at: http://${hostname}:${webport}`)
})
  • 界面结构
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>WebSocket</title>
<script src="WsClient.js" charset="utf-8"></script>
</head>
<body>
    <h1> chat room </h1>
    <div id="content" name="name" style="overflow-y: scroll; width: 400px; height: 300px; border: solid 1px #000;color:pink;"></div>
    <br />
    <div>
        <input type="text" id="msg" style="width: 200px;">
    </div>
    <button id="submit" style="background:red">提交</button>
    <script src="./wsClient.js"></script>
    <script>
        document.querySelector('#submit').addEventListener('click', function () {
                var msg2 = msg.value
                ws.send(msg2)
                msg.value = ''
        }, false)
    </script>
</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值