C# 即时通讯
我正在用 C# 开发一个即时消息程序(仅供学习)。
只是想知道我的方法是对还是错。
我创建了一个 Client 类,其中包含 NetworkStream 和读/写函数。
服务器为每个客户端创建一个新线程,该线程侦听任何新消息。
还有更好的办法吗?
I'm working on a instant messaging program in C#(for learning only).
Just wanna to know if my way is right or wrong.
I created a Client class whice contains a NetworkStream and Read/Write functions.
The server creates a new thread for every client, the thread listen for any new messages.
Any better way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不一定需要为每个客户端生成一个线程。我会研究观察者设计模式,因为它解决了发布-订阅问题,这是查看即时消息应用程序的好方法,特别是如果您希望一个讲话者有多个侦听器。
这是一个很好的起点:http://www.blackwasp.co.uk/Observer.aspx 。此链接讨论观察者模式并提到即时消息: http://www.oodesign.com/observer -pattern.html。
您可能会发现单线程方法可能能够跟上大量消息。根据您设计类的方式,您可能会发现将整个对话放在自己的线程中很有用。您还应该考虑使用队列来处理传入和传出消息,并在自己的线程中使用队列读取器。
听起来是一个有趣的项目。
You don't necessarily need to spawn a thread for each client. I'd investigate the Observer design pattern as it addresses the publish-subscribe problem, which is a good way to look at an instant messaging application, particularly if you want multiple listeners to one talker.
Here's a good place to start: http://www.blackwasp.co.uk/Observer.aspx. This link discusses the Observer pattern and mentions instant messaging: http://www.oodesign.com/observer-pattern.html.
You may find that a single-threaded approach may be able to keep up with a lot of messages. Depending upon how you design you classes you may find it useful to put entire conversations in their own thread. You should also think about using queues to handle incoming and outgoing messages, with queue readers in their own thread as well.
Sounds like a fun project.
尝试一下 WCF。 这里是一个很好的示例。
Try WCF. Here is a nice sample.