TCPClient 类实现网络互联、通信
TcpClient 为 TCP 网络服务提供客户端连接。
System.Object
System.Net.Sockets.TcpClient
[C#] public class TcpClient : IDisposable
备注
TcpClient 类提供了一些简单的方法,用于在同步阻塞模式下通过网络来连接、发送和接收流数据。
为使 TcpClient 连接并交换数据,使用 TCP ProtocolType 创建的 TcpListener 或 Socket 必须侦听是否有传入的连接请求。可以使用下面两种方法之一连接到该侦听器:
?创建一个 TcpClient,并调用三个可用的 Connect 方法之一。
?使用远程主机的主机名和端口号创建 TcpClient。此构造函数将自动尝试一个连接。
注意 如果要在同步阻塞模式下发送无连接数据报,请使用 UdpClient 类。
对继承者的说明: 要发送和接收数据,请使用 GetStream 方法来获取一个 NetworkStream。调用 NetworkStream 的 Write 和 Read 方法与远程主机之间发送和接收数据。使用 Close 方法释放与 TcpClient 关联的所有资源。
示例 C#下面的示例建立 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. 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();}
using System;using System.Collections.Generic;using System.Text;using System.Net.Sockets;using System.Net; namespace tcpclient{ class Program { private static int portNum = 11000; private static string hostName = Dns.GetHostName().ToString(); public static void Main(String[] args) { try { Console.WriteLine("主机名字:"+ Dns.GetHostName()); Console.WriteLine("主机IP地址:"+ Dns.GetHostAddresses(Dns.GetHostName())[0]); TcpClient client = new TcpClient(hostName, portNum); NetworkStream ns = client.GetStream(); byte[] bytes = new byte[1024]; int bytesRead = ns.Read(bytes, 0, bytes.Length); //将字节流解码为字符串 Console.WriteLine(Encoding.ASCII.GetString(bytes, 0, bytesRead)); client.Close(); } catch (Exception e) { Console.WriteLine(e.ToString()); } } }}
using System;using System.Collections.Generic;using System.Text;using System.Net.Sockets;using System.Net;namespace tcpclient{ class Program { private const int portNum = 11000; static void Main(string[] args) { bool done = false; //TcpListener listener = new TcpListener(portNum); //根据VS2005 MSDN 此方法已经过时,不再使用 // IPEndPoint类将网络标识为IP地址和端口号 TcpListener listener = new TcpListener(new IPEndPoint(IPAddress.Any, portNum)); listener.Start(); while (!done) { Console.Write("Waiting for connection..."); TcpClient client = listener.AcceptTcpClient(); Console.WriteLine("Connection accepted."); NetworkStream ns = client.GetStream(); byte[] byteTime = Encoding.ASCII.GetBytes(DateTime.Now.ToString()); try { ns.Write(byteTime, 0, byteTime.Length); ns.Close(); client.Close(); } catch (Exception e) { Console.WriteLine(e.ToString()); } } listener.Stop(); } }}
using System;using System.Net.Sockets;using System.Text;using System.Net;using System.Threading;namespace Udpclient2{ class Program { static void Main(string[] args) { try { UdpClient udpClient = new UdpClient(12000); string returnData = "client_end"; do { Console.WriteLine("服务器端接收数据:............................."); IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0); // 此处通过引用传值,获得客户端的IP地址及端口号 Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint); //此处获得客户端的数据 returnData = Encoding.UTF8.GetString(receiveBytes); //Encoding.ASCII.GetString(receiveBytes); 此处若用ASCII,不能正确处理中文 Console.WriteLine("This is the message server received: " + returnData.ToString()); Thread.Sleep(3000); Console.WriteLine("向客户端发送数据:............................."); udpClient.Connect(Dns.GetHostName().ToString(), 11000); // Sends a message to the host to which you have connected. string sendStr = "我来自服务器端:" + DateTime.Now.ToString(); Byte[] sendBytes = Encoding.UTF8.GetBytes(sendStr); //Byte[] sendBytes = Encoding.ASCII.GetBytes(sendStr); 此处若用ASCII,不能正确处理中文 udpClient.Send(sendBytes, sendBytes.Length); Console.WriteLine("This is the message server send: " + sendStr); } while (returnData != "client_end"); } catch (Exception e) { Console.WriteLine(e.ToString()); } } }}
using System;using System.Net.Sockets;using System.Text;using System.Net;namespace Udpclient{ class Program { static void Main(string[] args) { try { UdpClient udpClient = new UdpClient(11000); //向服务器发送数据 udpClient.Connect(Dns.GetHostName().ToString(), 12000); // Sends a message to the host to which you have connected. string sendStr = "我来自客户端:" + DateTime.Now.ToString(); Byte[] sendBytes = Encoding.UTF8.GetBytes(sendStr); //Byte[] sendBytes = Encoding.ASCII.GetBytes(sendStr); 此处若用ASCII,不能正确处理中文 udpClient.Send(sendBytes, sendBytes.Length); Console.WriteLine("This is the message client send: " + sendStr); //等待服务器的答复,收到后显示答复,并结束对话 IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0); // 此处通过引用传值,获得客户端的IP地址及端口号 Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint); //此处获得服务器端的数据 string returnData = Encoding.UTF8.GetString(receiveBytes); //Encoding.ASCII.GetString(receiveBytes); 此处若用ASCII,不能正确处理中文 Console.WriteLine("This is the message come from server: " + returnData.ToString()); udpClient.Close(); } catch (Exception e) { Console.WriteLine(e.ToString()); } } }}