将weoSocket的操作封装差个模块,这样不会显的主入口非常臃肿

    1. const socketIO = require('socket.io');
    2. let userList= []
    3. module.exports = function (server) {
    4. const io = socketIO(server);
    5. io.on('connection', (socket) => {
    6. let curUser = ''
    7. // 登录
    8. socket.on('login', (name) => {
    9. /**
    10. * 判断用户名不是搜有人,和用户名是否已经存在啦
    11. * 如果用户名为true 将其返回一个true
    12. */
    13. if (name == '所有人' || userList.filter(ele => ele.name == name).length > 0) {
    14. socket.emit('login', false);
    15. } else {
    16. curUser = name;
    17. userList.push({
    18. name,
    19. socket,
    20. });
    21. socket.emit('login', true);
    22. socket.broadcast.emit('userin', name);
    23. }
    24. })
    25. /**
    26. * 获取所有在线用户
    27. */
    28. socket.on('users', () => {
    29. const list = userList.map((ele) => ele.name);
    30. socket.emit('users',list);
    31. });
    32. socket.on('msg', ({msg, to}) => {
    33. if(to == null) {
    34. // 发送给所有人
    35. socket.broadcast.emit('newmsg',{
    36. form: curUser,
    37. msg,
    38. to,
    39. })
    40. }else {
    41. // 发送给某个人
    42. const receiveUser = userList.filter(ele => ele.name == to);
    43. if(receiveUser.length < 1) return;
    44. receiveUser[0].socket.emit('newmsg', {
    45. form: curUser,
    46. msg,
    47. to,
    48. });
    49. }
    50. })
    51. /**
    52. * 用户退出登录
    53. */
    54. socket.on('disconnect', res => {
    55. userList = userList.filter(ele => ele.name != curUser)
    56. socket.broadcast.emit('userout', curUser)
    57. });
    58. });
    59. };