C# 之 TcpClient和Socket

来源:互联网 发布:苹果笔记本办公软件 编辑:程序博客网 时间:2024/04/29 08:08

OSI七层网络架构

OSI中的层 功能 TCP/IP协议族
应用层 文件传输,电子邮件,文件服务,虚拟终端; TFTP,HTTP,SNMP,FTP,SMTP,DNS,Telnet
表示层 数据格式化,代码转换,数据加密; 没有协议
会话层 解除或建立与别的接点的联系; 没有协议
传输层 提供端对端的接口; TCP,UDP
网络层 为数据包选择路由; IP,ICMP,RIP,OSPF,BGP,IGMP
数据链路层 传输有地址的帧以及错误检测功能; SLIP,CSLIP,PPP,ARP,RARP,MTU
物理层 以二进制数据形式在物理媒体上传输数据; ISO2110,IEEE802,IEEE802.2

简单的理解

物理层:HUB,网线
链路层:MAC,ARP,交换机
网络层:IP,ICMP,IGMP,路由器
传输层:TCP,UDP
会话层:HTTP,SMTP,FTP,POP3
表示层:SOAP,SSL

应用层:WebService的Method

Socket是对网络层操作
TcpClient是对传输层操作

ASP.NET是对会话层操作

TcpClient是Socket的基础上的封装,为了简化一部分Socket的功能。
1>Socket支持TCP,UDP,IP包,Stream,Dgram等诸多类型
2>而TcpClient只支持TCP和Stream
一般的应用,用TcpClient可以了,或者使用NetStream,如果要做点高级的事情,建议用Socket做。


TcpClient 类(为 TCP 网络服务提供客户端连接)

备注
TcpClient 类提供了一些简单的方法,用于在同步阻止模式下通过网络来连接、发送和接收流数据。
为使 TcpClient 连接并交换数据,使用 TCP ProtocolType 创建的 TcpListener 或 Socket 必须侦听是否有传入的连接请求。可以使用下面两种方法之一连接到该侦听器:
创建一个 TcpClient,并调用三个可用的 Connect 方法之一。
使用远程主机的主机名和端口号创建 TcpClient。此构造函数将自动尝试一个连接。

Note注意
如果要在同步阻止模式下发送无连接数据报,请使用 UdpClient 类。
继承说明 要发送和接收数据,请使用 GetStream 方法来获取一个 NetworkStream。调用 NetworkStream 的 Write 和 Read 方法与远程主机之间发送和接收数据。使用 Close 方法释放与 TcpClient 关联的所有资源。

下面的代码示例建立 TcpClient 连接

static void Connect(String server, String message) {  try   {    // Create a TcpClient.    // Note, for this client to work you need to have a TcpServer     // connected to the same address as specified by the server, port    // combination.    Int32 port = 13000;    TcpClient client = new TcpClient(server, port);    // Translate the passed message into ASCII and store it as a Byte array.    Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);             // Get a client stream for reading and writing.   //  Stream stream = client.GetStream();    NetworkStream stream = client.GetStream();    // Send the message to the connected TcpServer.     stream.Write(data, 0, data.Length);    Console.WriteLine("Sent: {0}", message);             // Receive the TcpServer.response.    // Buffer to store the response bytes.    data = new Byte[256];    // String to store the response ASCII representation.    String responseData = String.Empty;    // Read the first batch of the TcpServer response bytes.    Int32 bytes = stream.Read(data, 0, data.Length);    responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);    Console.WriteLine("Received: {0}", responseData);             // Close everything.    stream.Close();             client.Close();           }   catch (ArgumentNullException e)   {    Console.WriteLine("ArgumentNullException: {0}", e);  }   catch (SocketException e)   {    Console.WriteLine("SocketException: {0}", e);  }  Console.WriteLine("\n Press Enter to continue...");  Console.Read();}

转载 C# 之 TcpClient和Socket

阅读全文
0 0
原创粉丝点击