HTTP stream server: threads?
I already wrote here about the http chat server I want to create: Alternative http port? This http server should stream text to every user in the same chat room on the website. The browser will stay connected and wait for further html code. (yes that works, the browser won't reject the connection).
I got a new question: Because this chat server doesn't need to receive information from the client, it's not necessary to listen to the client after the server sent its first response. New chat messages will be send to the server on a new connection. So I can open 2 threads, one waiting for new clients (or new messages) and one for the html streaming. Is this a good idea or should I use one thread per client? I don't think it's good to have one thread/client when there are many chat users online, sinc开发者_运维知识库e the server should handle multiple different chats with their own rooms.
3 posibilities: 1. One thread for all clients, send text to each client successive - there shouldn't be much lag since it's only text this will be like: user1.send("text");user2.send("text"),... 2. One thread per chat or chatroom 3. One thread per chat user - ... many...
Thank you, I haven't done much with sockets yet ;).
Right now, you seem to be thinking in terms of a given thread always carrying out a given (type of) task. While that basic design can make sense, to produce a scalable server like this, it generally doesn't work very well.
Often a slightly more abstract viewpoint works out better: you have tasks that need to get done, and threads that do those tasks -- but a thread doesn't really "care" about what task it executes.
With this viewpoint, you simply need to create some sort of data structure that describes each task that needs to be done. When you have a task you want done, you fill in a data structure to describe the task, and hand it off to get done. Somewhere, there are some threads that do the tasks.
In this case, the exact number of threads becomes mostly irrelevant -- it's something you can (and do) adjust to fit the number of CPU cores available, the type of tasks, and so on, not something that affects the basic design of the program.
I think easiest pattern for this simple app is to have pool of threads and then for each client pick available thread or make it wait until one becomes available.
If you want serious understanding of http server architecture concepts google following:
- apache architecture
- nginx architecture
精彩评论