C# 是否可以在 Socket 和 TcpClient 对象之间进行转换?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/203147/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 17:51:21  来源:igfitidea点击:

Is it possible to convert between Socket and TcpClient objects?

c#.netsocketstcpclientsystem.net

提问by Neil C. Obremski

Here's another C#/.NET question based merely on curiousity more than an immediate need...

这是另一个 C#/.NET 问题,仅仅基于好奇而不是迫切需要......

If you had a Socketinstance and you wanted to wrap it in the higher-level TcpClientclass, is that possible and how would you do it?

如果你有一个Socket实例并且你想把它包装在更高级别的TcpClient类中,这可能吗?你会怎么做?

Conversely if you have an instance of TcpClient, is it possible to get the underlying Socket?

相反,如果您有 的实例TcpClient,是否有可能获得底层Socket

采纳答案by Jorge Ferreira

If you had a Socket instance and you wanted to wrap it in the higher-level TcpClient class, is that possible and how would you do it?

如果您有一个 Socket 实例并且您想将它包装在更高级别的 TcpClient 类中,这可能吗?您将如何做?

Socket socket = ...;
TcpClient client = new TcpClient();
client.Client = socket;

Conversely if you have an instance of TcpClient, is it possible to get the underlying Socket?

相反,如果您有一个 TcpClient 实例,是否可以获取底层 Socket?

Get the underlying Socket using TcpClient.Clientproperty.

使用TcpClient.Client属性获取底层 Socket 。

回答by Jobi Joy

From TcpClient to Socket is very easy. tcpClientInstance.Clientis the underlying Socket instance.

从 TcpClient 到 Socket 非常容易。tcpClientInstance.Client是底层的 Socket 实例。