C# 之 TcpClient和Socket

本文介绍了C#中的TcpClient和Socket在网络层面上的作用。TcpClient是基于Socket的封装,简化了TCP连接的操作,适用于一般应用程序。而Socket提供了更底层的访问,支持TCP、UDP等多种网络协议,适合进行更复杂的数据交换。示例代码展示了如何使用TcpClient建立连接。
摘要由CSDN通过智能技术生成

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();
}
  • 6
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C#中的SocketTcpClient都是用于网络编程的类,可以用于建立客户端和服务器之间的连接。其中,Socket是一个底层的类,提供了更多的灵活性和控制权,而TcpClient则是基于Socket类的更高级别的封装,使用起来更加方便。 下面是一个使用TcpClient类建立客户端连接的例子: ```csharp using System; using System.Net; using System.Net.Sockets; class Program { static void Main(string[] args) { // 设置服务器IP和端口号 string serverIP = "127.0.0.1"; int serverPort = 8888; // 创建TcpClient对象并连接服务器 TcpClient client = new TcpClient(); client.Connect(serverIP, serverPort); // 发送数据 string message = "Hello, server!"; byte[] data = System.Text.Encoding.UTF8.GetBytes(message); NetworkStream stream = client.GetStream(); stream.Write(data, 0, data.Length); // 接收数据 data = new byte[1024]; int length = stream.Read(data, 0, data.Length); message = System.Text.Encoding.UTF8.GetString(data, 0, length); Console.WriteLine("Received message from server: {0}", message); // 关闭连接 stream.Close(); client.Close(); } } ``` 上述代码中,我们首先创建了一个TcpClient对象,并使用Connect方法连接到指定的服务器IP和端口号。然后,我们使用GetStream方法获取与服务器通信的NetworkStream对象,并使用Write方法向服务器发送数据。接着,我们使用Read方法从服务器接收数据,并将其转换为字符串输出。最后,我们关闭了与服务器的连接。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值