mysql数据库
下载后先在文件夹下新建my.ini配置文件,可以去网上搜一下。
新建一个data空文件夹
cmd 运行管理员模式,打开 进入bin下,mysqld –initialize -console 会对数据库进行初始化,并能得到一个随机密码(8.0版本)
之后运行命令行 mysqld –install 安装
net start mysql 运行数据库
mysql -u root -p 进入修改密码
用初始密码登录,修改密码。完成配置。
打开数据库也可以在电脑服务里面开启 / 关闭
mysql语言
增 INSERT INTO 表(字段列表) VALUE(‘值‘’)
INSERT INTO ‘my-data(username,password)’ VALUE(‘zhangsan’,’1232’)
删 DELETE FROM 表WHERE 条件
DELETE FROM my-data WHERE username=’zhangsan
改 UPDATA 表 SET 字段-新值,字段-新值… WHERE 条件
UPDATA my-data SET name-lisi, password-321… WHERE username=zhangsan
查 SELECT 字段列表FROM 表 WHERE 条件
SELECT password FROM my-data WHERE username=zhangsan
websocket.io
const http = require('http')
const io = require('socket.io')
const fs = require('fs')
const mysql = require('mysql')
//引入数据库
let db = mysql.createPool({host:'localhost',user:'root',password:'123456',database:'mysql'})
//http服务
const httpServer = http.createServer((req, res) => {
fs.readFile(`www${req.url}`, (err, data) => {
if (err) {
res.writeHeader(404)
res.write('not found')
} else {
res.write(data)
}
res.end()
})
})
httpServer.listen(8080)
//io服务
let socker = []
const seServer = io.listen(httpServer)
seServer.on('connection', (sock) => {
socker.push(sock) // 添加所有来客
// 记录当前状态
let cur_username = ''
let cur_id = 0
//校验注册
sock.on('reg', (user, password) => { // 监听来自js前台的数据
//1.校验数据
if (!regs.username test(user)) {
sock.emit('reg-ret', 1, '用户名不符合规范') // 返回一个接口给前台(‘事件’,code,‘msg’)
} else if(!regs.password test(password)) {
sock.emit('reg-ret', 1, '密码不符合规范')
} else {
// 2. 用户是否被注册 --数据库查询
db.query('SELECT ID FROM my_user WHERE username=`${user}`', (err, data) => {
if (err) {
sock.emit('reg-ret', 1, '数据库出错')
} else if (data.length > 0) {
sock.emit('reg-ret', 1, '该用户已被注册')
} else {
// 3.插入数据
db.query('INSERT INTO my_user(username, password, online) VALUE(`${user}`,`${password}`, 0)', (err, data) => {
if (err) {
sock.emit('reg-ret', 1, '数据库出错')
} else {
sock.emit('reg-ret', 0, '注册成功')
}
})
}
})
}
})
//校验登录
sock.on('login', (user, password) => {
// 校验数据
if (!regs.username.test(user)) {
sock.emit('login-ret', 1, '用户名不符合规范')
} else if (!regs.password test(password)) {
sock.emit('login-ret', 1, '密码不符合规范')
} else {
// 查询
db.query(`SELECT ID, username FROM my_user WHERE username=${user}`, (err, data) => {
if (err) {
sock.emit('login-ret', 1, '数据库出错')
} else if (data.length === 0) {
sock.emit('login-ret', 1, '该用户不存在')
} else if (data[0].password !== password) {
sock.emit('login-ret', 1, '用户名或密码错误')
} else {
// 修改登录状态
db.query(`UPDATA my_user SET online=1 WHERE ID=${data[0].ID}`, err => {
if (err) {
sock.emit('login-ret', 1, '数据库出错')
} else {
sock.emit('login-ret', 0, '登陆成功')
cur_id = data[0].ID
cur_username = user
}
})
}
})
}
})
//发言
sock.on('msg', (text) => {
if(!text) {
scok.emit('msg-ret', 1, '发言不能为空')
} else {
// 广播所有人
socker.forEach((item) => {
item.emit('msg', cur_username, text)
})
sock.emit('msg-ret', 0, '发言成功')
}
})
//离线
sock.on('disconnect', () => {
db.query(`UPDATA my_user SET online=0 where ID = ${data[0].ID}`, (err) => {
if (err) {
console.log('数据库有错')
}
cur_id = 0
cur_username = ''
socker = socker.filter((item) => item != sock) //当离线时候,去掉来客
})
})
})
html文件
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Documenttitle>
head>
<style>
.mine{
background-color: green
}
style>
<script src="http://localhost:8080/socket.io/socket.io.js">script>
<script>
let sock = io.connet('ws://localhost:8080/')
window.onload = funciton () {
let btn1 = document.getElementById('btn1')
let btn2 = document.getElementById('btn2')
let cur_username = ''
let username = document.getElementById('username')
let password = document.getElementById('password')
let oUl = document.getElementById('oUl')
let text = document.getElementById('text')
btn1.onclick = function () {
sock.emit('reg', username.value(), password.value())
}
//注册
sock.on('reg-ret', (code, msg) => {
if (code === 1) {
alert('注册失败' + msg)
} else if (code === 0) {
alert('注册成功')
}
})
//登录
sock.on('login-ret', (code, msg) => {
if (code === 1) {
alert('注册失败' + msg)
} else if (code === 0) {
alert('注册成功')
cur_username = username.value()
}
})
btn2.onclick = function () {
sock.emit('login', username.value(), password.value())
}
//发言
sock.on('msg_ret', (code, msg) => {
if (code === 1) {
alert('发言失败' + msg)
} else {
let oLi = document.createElement('li')
oLi.classnName = 'mine'
oLi.innerHTNL = `${cur_username}:</h2>
${text.value()}
p>`
oUl.appendChild(oLi)
text.value = ''
}
})
sock.on('msg', (name, text) => {
let oLi = document.createElement('li')
oLi.innerHTNL = `${name}:</h2>
${text}
p>`
oUl.appendChild(oLi)
})
}
script>
<input type="text" id="username">
<input type="password" id="password">
<input type="button" value="注册" id="btn1">
<input type="button" value="登录" id="btn2">
<hr>
<textarea name="text" id="text" cols="80" rows="5">textarea>
<input type="button" value="发言" id="btn-send"><br>
<ul id="oUl">
ul>
<body>
body>
html>
用express框架
var express = require('express');
var app = express();
var http = require('http').Server(app); //将express注册到http中
var io = require('socket.io')(http);
//session公式:
var session = require('express-session');
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true
}));
app.set('view engine','ejs');
app.use(express.static('./public'));
app.get('/',function(req,res,next){
res.render('login.ejs');
});
var user = [];
//登录核查
app.get('/check',function(req,res,next){
var username = req.query.username;
if(user.indexOf(username) != -1){ //indexof()-1表示该数组中没有该数
res.send('该用户名已被占用');
return;
}else if(!username){
res.send('请登录');
return;
} else{
user.push(username);
req.session.login = 1;
req.session.username = username;
console.log(req.session.username)
res.redirect('/chat'); // 跳转
}
})
app.get('/chat',function(req,res,next){
if(!req.session.username){
res.redirect('/');
return;
}
res.render('chat.ejs',{
'login': req.session.login = 1? true: false,
'username': req.session.username
})
})
io.on('connection',function(socket){
//监听join事件
socket.on('join',function(name){
console.log(name)
// user[name] = socket; //user.push(name);
io.emit('join',name); //广播新用户给全体成员
})
//监听message事件
socket.on('message',function(msg){
io.emit('message',msg);//广播新消息给全体成员
})
})
http.listen(3000);
chat.ejs
<html>
<head>
<meta charset="utf-8" />
<title><%= username%>chartroomtitle>
<style type="text/css">
body{
font: 13px helvetica,arial;
}
form{
background: #000;
padding: 3px;
position: fixed;
bottom: 0;
width: 100%;
}
form input{
border: 0;
padding: 10px;
width: 85%;
margin-right: 0.5%;
}
form button{
width: 9%;
background: rgb(130,224,255);
border: none;
padding: 10px;
}
#message{
list-style: none;
margin: 0;
padding: 0;
}
#message li{
padding: 5px 10px;
}
#message li:nth-child(odd){
background: #eee;
}
style>
head>
<body>
<h3>
欢迎 <%= username%>
h3>
<ul id="message">ul>
<form action="" >
<input type="" name="message" id="m" value="" />
<button>发送button>
form>
body>
<script type="text/javascript" src="/socket.io/socket.io.js">script>
<script src="./js/jquery-1.11.3.min.js">script>
<script type="text/javascript">
var socket = io();
// console.log(<%= username%>)
<%if(login){%>
// var name = prompt('请确认您的名称:');
var name = $('h3').html();
// console.log()
//发送昵称给后端
socket.emit('join',name);
// document.title = name + '的群聊'
//接受到服务器发送来的join事件
socket.on('join',function(name){
addLine(name + '加入群聊');
})
<%}%>
$('form').submit(function(){
var msg = $('#m').val();
socket.emit('message',{
"neirong" : $('#m').val()
}); //将消息发送给服务器
$('#m').val(''); //清空输入框
return false;//阻止form提交
})
//接受后台发来的message事件
socket.on('message',function(msg){
$("#message").prepend("" + msg.neirong + "");
})
function addLine(msg){
$('#message').append($('' ).text(msg));
}
script>
html>
login.ejs
<html>
<head>
<meta charset="utf-8" />
<title>chartroomtitle>
<style type="text/css">
.box{
width: 30%;
margin: 100px auto;
height: 200px;
background: #ccc;
}
#username{
margin: 20px 10px;
}
p{
display: inline;
margin-left: 30px;
}
#submit{
margin-left: 30px;
margin-top: 20px;
}
style>
head>
<body>
<div class="box">
<form action="/check" >
<p>昵称:p><input type="text" name="username" id="username" value="" /><br />
<p>密码:p> <input type="password" id="password" name="password"/><br />
<input type="submit" name="submit" id="submit" value="登录" />
form>
div>
body>
script>
html>