3

有人可以指出我学习如何在 C#/.net 3.5 中建立网络的正确方向吗?欢迎代码示例和解释。基本上我正在寻找如何做异步/多线程服务器/客户端模型。

我对如何使用 WinSock 在 C++ 中完成此任务的基础知识相当满意,但尽管我的所有研究似乎都无法在 C# 中掌握这个概念。

感谢您提供的任何帮助:)

4

3 回答 3

16

如果 WCF 满足您的需求,那么值得一看。ZeroC和其他替代的更高级别的库存在。否则,如果您需要的话,有几种不同的方法可以更接近套接字级别。

TcpClient/UdpClient

这些在底层套接字周围提供了一个相对较薄的包装。它本质上在套接字上提供了一个流。您可以在 NetworkStream 上使用异步方法(BeginRead 等)。我不喜欢这个,因为包装器没有提供那么多,而且它往往比直接使用套接字更尴尬。

插座 - 选择

This provides the classic Select technique for multiplexing multiple socket IO onto a single thread. Not recommended any longer.

Socket - APM Style

The Asynchronous Programming Model (AKA IAsyncResult, Begin/End Style) for sockets is the primary technique for using sockets asynchronously. And there are several variants. Essentially, you call an async method (e.g., BeginReceive) and do one of the following:

  1. Poll for completion on the returned IAsyncResult (hardly used).
  2. Use the WaitHandle from the IAsyncResult to wait for the method to complete.
  3. Pass the BeginXXX method a callback method that will be executed when the method completes.

The best way is #3 as it is the usually the most convenient. When in doubt, use this method.

Some links:

.NET 3.5 High Performance Sockets

.NET 3.5 introduced a new model for async sockets that uses events. It uses the "simplified" async model (e.g., Socket.SendAsync). Instead of giving a callback, you subscribe to an event for completion and instead of an IAsyncResult, you get SocketAsyncEventArgs. The idea is that you can reuse the SocketAsyncEventArgs and pre-allocate memory for socket IO. In high performance scenarios this can be much more efficient that using the APM style. In addition, if you do pre-allocate the memory, you get a stable memory footprint, reduced garbage collection, memory holes from pinning etc. Note that worrying about this should only be a consideration in the most high performance scenarios.

Summary

For most cases use the callback method of the APM style unless you prefer the style of the SocketAsyncEventArgs / Async method. If you've used CompletionPorts in WinSock, you should know that both of these methods use CompletionPorts under the hood.

于 2008-10-17T01:57:42.050 回答
2

在 .NET 3.5 世界中,您绝对应该学习Windows Communication Foundation - .NET 网络框架。

有用的链接:

同步和异步操作(在 WCF 中)

您可以在 StackOverflow 浏览带有 WCF标记的帖子上找到有用的 WCF 信息

于 2008-10-17T00:52:44.787 回答
0

这取决于你想关注什么。

如果您想专注于功能并将管道留给框架,请从 Windows Communication Foundation 开始。

如果您想建立自己的管道,请使用System.Net.Sockets.Socket类。

于 2008-10-17T00:53:53.130 回答