專案碼源:https://github.com/JavonHuang/socketIM
介面文件:http://www.docway.net/dashboard/project/1T...
環境要求:
mysql資料庫:https://dev.mysql.com/downloads/mysql/
redis:https://redis.io/download
工具:
資料庫連線工具(推薦):Navicat
redis視覺化工具(推薦):rdm
一、搭建專案
1.執行npm init命令初始化專案。
{
"name": "imserver",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
},
"author": "",
"license": "ISC",
}
2.安裝typescript以及其依賴庫。
npm i --save-dev typescript ts-node nodemon // nodemon主要用於熱載入APP
3.安裝koa依賴
npm i koa
npm i --save-dev @types/koa koa-controllers
4.安裝多環境外掛
npm i cross-env
{
"name": "imserver",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "cross-env NODE_ENV=production tsc && node dist/app.js",
"watch-server": "cross-env NODE_ENV=dev nodemon --watch ./src/app.ts -e ts,tsx --exec ts-node ./src/app.ts"
},
"author": "",
"license": "ISC",
"dependencies": {
"cross-env": "^7.0.2",
"koa": "^2.11.0",
"koa-controllers": "^0.1.6",
"jsonwebtoken": "^8.5.1",
"mysql": "^2.18.1"
},
"devDependencies": {
"@types/koa": "^2.11.2",
"nodemon": "^2.0.2",
"ts-node": "^8.6.2",
"typescript": "^3.8.3"
}
}
5.設定tsconfig.json檔案編譯輸出路徑
{
"compileOnSave": true,
"compilerOptions": {
/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
// "lib": [], /* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
// "declaration": true, /* Generates corresponding '.d.ts' file. */
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
"sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
"outDir": "dist", /* Redirect output structure to the directory. */
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
/* Strict Type-Checking Options */
"strict": true, /* Enable all strict type-checking options. */
"noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
"strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
"noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
/* Module Resolution Options */
"moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
"baseUrl": "./", /* Base directory to resolve non-absolute module names. */
"paths": {
"*":[
"node_modules/*", //根據專案的路徑指定
"src/*" //根據專案的路徑指定
]
}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
/* Experimental Options */
"experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
"emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
/* Advanced Options */
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
},
"include": [
"./src/**/*"
]
}
6.設定路由控制器
import Koa = require('koa');
import { useControllers } from 'koa-controllers';
import {config,jwtKey} from './config/config';
let controllersPath:string='/controllers/*.js';//根據您不同環境進行檔案格式匹配
if(process.env.NODE_ENV=='dev'||process.env.NODE_ENV=='development'){
controllersPath='/controllers/**/*.ts'
}
const app = new Koa();
useControllers(app, __dirname + controllersPath, {
multipart: {
dest: './uploads'
}
});
app.listen(3000);
console.log("env:",process.env.NODE_ENV);
console.log('Server is runing !!')
console.log('click url to:http://localhost:3000')
process.on ('SIGTERM', ()=>{
console.log('Server is exit !!')
process.exit();
});
process.on ('SIGINT', ()=>{
console.log('Server is exit !!')
process.exit();
});
7.本地debug typescript,配置launch.json檔案
{
// 使用 IntelliSense 瞭解相關屬性。
// 懸停以檢視現有屬性的描述。
// 欲瞭解更多資訊,請訪問: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Koa Program",
"runtimeArgs": [
"--nolazy",
"-r",
"ts-node/register",
],
"args": [
"${workspaceFolder}/src/app.ts"
],
"env": {
"DEBUG": "yuedun:*,-not_this",
"NODE_ENV": "development"
},
"sourceMaps": true,
"cwd": "${workspaceFolder}",
"protocol": "inspector",
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen"
}
]
}
配置之後即可打斷點除錯程式
8.安裝mysql資料連線和jwt token
npm i jsonwebtoken mysql --save
9.安裝伺服器跨域處理外掛koa2-cors
npm i koa2-cors
//跨域處理
app.use(cors({
credentials: true//解決socket.io跨域
}));
10.安裝請求json資料處理外掛koa-json
npm i koa-json
11.安裝redis外掛
npm i redis
12.安裝socket.io外掛
npm i socket.io
二、資料配置(Mac)
mysql安裝之後有可能不支援儲存emoji字元,需修改其配置。
/usr/local/mysql-5.7.18-macos10.12-x86_64/support-files路徑下新增my.cnf檔案(已存在則修改)如下
同時修改資料字元為:utf8mb4
# Example MySQL config file for small systems.
#
# This is for a system with little memory (<= 64M) where MySQL is only used
# from time to time and it's important that the mysqld daemon
# doesn't use much resources.
#
# MySQL programs look for option files in a set of
# locations which depend on the deployment platform.
# You can copy this option file to one of those
# locations. For information about these locations, see:
# http://dev.mysql.com/doc/mysql/en/option-files.html
#
# In this file, you can use all long options that a program supports.
# If you want to know which options a program supports, run the program
# with the "--help" option.
# The following options will be passed to all MySQL clients
[client]
default-character-set=utf8mb4 # 修改此處預設資料集
#password = 123456
port = 3306
socket = /tmp/mysql.sock
# Here follows entries for some specific programs
# The MySQL server
[mysqld]
default-storage-engine=INNODB
character-set-server=utf8mb4 # 修改此處
collation-server= utf8mb4_unicode_ci # 對應也需要修改
port = 3306
socket = /tmp/mysql.sock
skip-external-locking
key_buffer_size = 16K
max_allowed_packet = 1M
table_open_cache = 4
sort_buffer_size = 64K
read_buffer_size = 256K
read_rnd_buffer_size = 256K
net_buffer_length = 2K
thread_stack = 128K
# Don't listen on a TCP/IP port at all. This can be a security enhancement,
# if all processes that need to connect to mysqld run on the same host.
# All interaction with mysqld must be made via Unix sockets or named pipes.
# Note that using this option without enabling named pipes on Windows
# (using the "enable-named-pipe" option) will render mysqld useless!
#
#skip-networking
server-id = 1
# Uncomment the following if you want to log updates
#log-bin=mysql-bin
# binary logging format - mixed recommended
#binlog_format=mixed
# Causes updates to non-transactional engines using statement format to be
# written directly to binary log. Before using this option make sure that
# there are no dependencies between transactional and non-transactional
# tables such as in the statement INSERT INTO t_myisam SELECT * FROM
# t_innodb; otherwise, slaves may diverge from the master.
#binlog_direct_non_transactional_updates=TRUE
# Uncomment the following if you are using InnoDB tables
#innodb_data_home_dir = /usr/local/mysql/data
#innodb_data_file_path = ibdata1:10M:autoextend
#innodb_log_group_home_dir = /usr/local/mysql/data
# You can set .._buffer_pool_size up to 50 - 80 %
# of RAM but beware of setting memory usage too high
#innodb_buffer_pool_size = 16M
#innodb_additional_mem_pool_size = 2M
# Set .._log_file_size to 25 % of buffer pool size
#innodb_log_file_size = 5M
#innodb_log_buffer_size = 8M
#innodb_flush_log_at_trx_commit = 1
#innodb_lock_wait_timeout = 50
[mysqldump]
quick
max_allowed_packet = 16M
[mysql]
no-auto-rehash
# Remove the next comment character if you are not familiar with SQL
#safe-updates
[myisamchk]
key_buffer_size = 8M
sort_buffer_size = 8M
[mysqlhotcopy]
interactive-timeout
三、UI效果圖
2.訊息列表
3.聊天列表
4.好友管理
5.群聊列表
6.群管理
本作品採用《CC 協議》,轉載必須註明作者和本文連結