dongrouyuan5685 2015-11-13 14:48
浏览 42
已采纳

使用websockets聊天应用程序

I have been able to use Websockets to create a chat application between users using https://github.com/ghedipunk/PHP-Websockets.

What the server does is stores all the created socket object variables in an array when each user connects to the socket. So, ultimately he creates an array which has info regarding all users with the socket object. And he loops through the array each time to retrieve the object of a user so that message can be sent to the respective socket.

This will be fine for small amount of users. But how do we handle huge amounts of users? I thought of storing socket objects in DB but then I came across this: How to save php socket resource in database?

Which says "Sockets have to be recreated and cannot be stored in DB".

So, is there any better option rather than recreating? And if I have to recreate the socket, how do I do it using the PHP-Websockets library?

Thanks in advance.

  • 写回答

2条回答 默认 最新

  • dousou1967 2015-11-13 15:30
    关注

    Socket cannot be saved on disk because it's existing connection. If you destroy the live object, the connection is closed and the user is disconnected.

    First I want to remind you, that memory and CPU might not be much of a concern. Node.js interpreter is actually surprisingly fast and WebSocket object hardly takes much memory. You will face other issues first, such as bandwidth problems, too many open connections etc.

    Possible tweaks I can think of:

    Multithreading - spawn child processes

    You can share sockets between node.js processes though, which is described here: https://nodejs.org/api/child_process.html#child_process_example_sending_server_object

    I cannot guarantee this will improve performance but it allows you to handle input from different users in parallel. I also don't know if WebSockets do support this, but I think so.

    Reducing socket overhead

    This is important to remember - you can't store the socket object on disk, but you can store most of other stuff. The socket object hardly takes significant amount of memory but if you store other info about user, it might slow you down. Redundant information should be stored in backend provided by database or something like that.

    Native core

    If you still encounter problems, you can write C/C++ native multithreaded core for your chat and let it do the heavy operations, such as looping through sockets and sending them messages. Have this core connected to Node.js server where your logic will be. Also not that you can write native plugins for Node.js.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 Windows 驱动开发版本疑问相关
  • ¥15 MAC 未能打开磁盘映像
  • ¥15 fastcap使用,二维导体输入问题
  • ¥15 hosts修改后不能访问
  • ¥15 关于化学反应速率C++编译问题/FLUENT
  • ¥20 Yolov5训练报错
  • ¥15 Unity发布gzip压缩的webgl之后让浏览器可以正常显示画面
  • ¥15 ASP.net Gridview插件数据更新失败问题
  • ¥15 有没有人知道这种提示怎么关?现在不做ts项目了不知道咋关了,求解,现在我以前的js项目都是这种提示了
  • ¥15 为什么mysql做了碎片化处理data_free还是很高