node.js(四)

node.js(四)

一.socket

1.net-socket

以下为代码示例:

/*
总服务器
*/
const net = require( 'net' ) //引入net模块,用于创建服务器/客户端
const server = net.createServer() // 创建服务器
const host = 'localhost' // 创建 域名
const port = 5000 // 创建端口
let count = 0
const clients = {} // 数组? 对象?
server.on('connection', ( client ) => { // 服务器通过connection事件连接客户端
// client指的是每一个连接的客户端
// client 是有多个 ,
// 问题: client会错乱 解决: 起名 数字编号 计数
client.name = ++count // 计数,给每一个客户端起名
clients[ client.name ] = client // 将每一个客户端放入clients中存储起来
client.on( 'data', msg => { // 服务器通过data事件来接收客户端发来的信息
// msg 就是客户端发来的信息 , msg这个信息是二进制
console.log( `客户端${ client.name }说:${ msg.toString() }` )
boardCaster( client,msg )
})
client.on( 'error', error => { // 服务器处理错误报出
console.log( 'error is: ' + error )
})
client.on( 'close', () => { // 服务端接收客户端正常下线行为
delete clients[ client.name ] // 从存储client的地方删除下线的客户端
console.log( `客户端${ client.name }下线了` )
})
})
// 我们需要将所有客户端发来的信息全部展示在服务器界面上【 聊天室 】 -》 广播
// 广播就是将所有的客户端以及客户端发来的信息展示在服务端界面上
function boardCaster ( client,msg ) { //广播的函数
for( var key in clients ){
// clients[ key ].write( `谁说了什么` ) // 写信息在服务端
clients[ key ].write( `客户端${ client.name }说:${ msg.toString() }` ) // 写信息在服务端
}
}
// 监听服务器
server.listen( port,host,() => {
console.log( `服务器运行在: http://${ host }:${ port }` )
})



/*
客户端
业务: 客户端现在要在终端输入内容,然后回车发送内容给服务器
解决: Node中提供了一个叫做 readline 的 模块用于读取命令行内容 【 单行读取 】
*/
const net = require( 'net' ) //引入net模块,用于创建服务器/客户端
const socket = net.Socket() //创建客户端
const host = 'localhost'
const port = 5000
const readline = require( 'readline') // 读取命令行
// 客户端连接服务器
socket.connect( port,host, () => {
socket.write( 'hello 我上线了' ) // 将一个信息发送给服务器
})
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
socket.on('data', msg => { // 客户端通过data事件展示信息,然后发送信息给服务器
console.log( msg.toString() )
say()
})
socket.on( 'error', ( error ) => { //处理错误报出
console.log( 'error is : ' + error )
})
socket.on( 'close', () => { // 客户端正常下线
console.log( `客户端下线了` )
})
function say () {
rl.question('请输入:', ( answer ) => {
if( answer === 'bye' ){
//表示正常下线
socket.destroy() // 客户端销毁
rl.end() // rl 读取命令行关闭
}else{
//表示正常聊天
socket.write( answer )
}
});
}



2.web-socket

代码示例:


/*
静态服务器
犯错: client下文件名称自定义的话,一定记得要加上去
举例: http://localhost:3000/yyb.html
*/
const express = require( 'express' )
const path = require( 'path' )
const app = express() // app对象的创建是为了绑定中间件
// 理解: 为了调用中间件( 函数 )
const port = 8000
const host = '10.31.158.70'
// 指定静态资源目录
/*
问题: 如果不指定静态资源目录,那么express启动的服务器就认为
/client/index.html 是一个路由
解决: 指定静态资源目录
*/
// console.log( __dirname ) // 当前文件所在的磁盘路径
app.use( express.static( path.join( __dirname, 'client') ))
app.listen( port,host,() => {
console.log( `服务器运行在: http://${ host }:${ port }` )
})


/*
通信的服务器
*/
const WebSocket = require('ws') // 引入ws模块
// 创建服务器
// const ws = new WebSocket( options ) options就是一个对象
const ws = new WebSocket.Server({
port: 5000,
host: '10.31.158.70'
})
let count = 0
const clients = {}
ws.on('connection', client => {
client.name = ++count
clients[client.name] = client
client.on('message', msg => { // 服务器通过message事件来接收客户端发来的信息
// 这里是用的message事件
console.log(`客户端${ client.name }说:${ msg }`)
boardCaster(client, msg)
})
client.on('close', () => {
delete clients[client.name]
console.log(`客户端${ client.name } 下线了`)
})
})
function boardCaster(client, msg) {
// 这里是用的send方法
for (var key in clients) {
clients[key].send(`客户端${ client.name }说: ${ msg }`)
}
}



/*
这个文件是用于客户端连接通信服务器
*/
const url = 'ws://10.31.158.70:5000'
const ws = new WebSocket( url )
ws.onopen = () => { //初次连接
ws.send('我进入了xxx的直播间')
}
ws.onmessage = msg => {
var content = document.querySelector('#content')
console.log( msg )
content.innerHTML += msg.data + '<br/>'
}


<!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>
</head>
<body>
<h1> 聊天室 </h1>
<div id="content" name="name" style="overflow-y: scroll; width: 400px; height: 300px; border: solid 1px #000"></div>
<br />
<div>
<input type="text" id="msg" style="width: 200px;">
</div>
<!-- <button id="submit">提交</button> -->
<script src="WsClient.js" charset="utf-8"></script>
<script>
var submit = document.querySelector('#submit')
var msg = document.querySelector('#msg')
// submit.onclick = function () {
// ws.send( msg.value ) //将信息发送通信服务器
// msg.value = ''
// }
document.onkeyup = function ( e ) {
if ( e.keyCode === 13 ) {
ws.send( msg.value )
msg.value = ''
}
}
</script>
</body>
</html>


二.express

代码示例:



const app = express() 

const port = 8090

const host = 'localhost'

const fs = require( 'fs' )


// express通过路由可以发送信息给前台


app.get('/home',( req,res,next ) => {
  /* 
    名词解释:
      1. req:  request   请求        
      2. res:  response  响应       
      3. next: 表示request到response的一个过程   

      next决定了请求和响应之间的连通

      经验: 
        req和前台有关   举例: req用来接收前台发来的数据
        res和后端有关: 举例: 后端返回给前端的结果

      req.query 接收前端发来的get请求携带的数据
  */

  // res.send('hello')

  console.log( req.query )

  fs.writeFile('./data/user.txt', JSON.stringify(req.query) , ( error ) => {
    console.log( '存储成功' )
  })


  res.json({
    ret: true,
    name: 'jack ma'
  })



})


app.listen( port,host, () => {

  console.log( `express搭建的服务器运行在:http://${ host }:${ port }` )

})

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值