C#网络编程中常用特性介绍
在C#网络编程中,有很多常用特性值得去了解和掌握。下面将会介绍几个常用的特性及其用法。
1. Socket
Socket是建立网络连接最基础的类之一。它提供了一组通信协议,并在套接字上实现这些协议。以下是一个简单的Socket示例,用于连接服务器、发送数据和接收数据。
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class SynchronousSocketClient {
public static void StartClient() {
byte[] bytes = new byte[1024];
try {
// 连接到远程服务器
IPHostEntry ipHostInfo = Dns.GetHostEntry("localhost");
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress, 11000);
Socket sender = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
try {
sender.Connect(remoteEP);
Console.WriteLine("Socket connected to {0}",
sender.RemoteEndPoint.ToString());
// 发送数据
byte[] msg = Encoding.ASCII.GetBytes("This is a test<EOF>");
int bytesSent = sender.Send(msg);
// 接收数据
int bytesRec = sender.Receive(bytes);
Console.WriteLine("Echoed test = {0}",
Encoding.ASCII.GetString(bytes, 0, bytesRec));
sender.Shutdown(SocketShutdown.Both);
sender.Close();
} catch (ArgumentNullException ane) {
Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
} catch (SocketException se) {
Console.WriteLine("SocketException : {0}", se.ToString());
} catch (Exception e) {
Console.WriteLine("Unexpected exception : {0}", e.ToString());
}
} catch (Exception e) {
Console.WriteLine(e.ToString());
}
}
}
2. WebClient
WebClient是一种方便的方式来进行HTTP访问。WebClient的用法类似于浏览器,可以处理GET/POST请求,可以设置引用、User-Agent等HTTP Header,并可以处理Cookie。下面是一个WebClient GET请求示例:
WebClient client = new WebClient();
string result = client.DownloadString("http://www.example.com/");
Console.WriteLine(result);
3. HttpWebRequest
HttpWebRequest是一个非常有用的类,可以用来作为发送HTTP请求的基本类,并以异步或同步方式处理响应。HttpWebRequest与WebClient区别在于它可以更加细致地控制请求头和响应内容。以下是一个发送HTTP POST请求的示例:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.example.com/");
request.Method = "POST";
string postData = "key1=value1&key2=value2";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
Console.WriteLine(responseString);
response.Close();
4. TcpListener
TcpListener是用于在TCP端口上监听传入连接的类。它提供了AcceptTcpClient方法来等待并接受传入的连接。以下是一个简单的TcpListener示例,它会等待客户端连接并接收数据。
public class TcpListenerExample {
public static void Main() {
TcpListener server = null;
try {
// 设置监听地址和端口号
Int32 port = 13000;
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
// 启动监听
server = new TcpListener(localAddr, port);
server.Start();
// 等待连接
Byte[] bytes = new Byte[256];
String data = null;
while (true) {
Console.Write("Waiting for a connection... ");
// 接受连接请求
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Connected!");
// 接收数据
data = null;
NetworkStream stream = client.GetStream();
int i;
while ((i = stream.Read(bytes, 0, bytes.Length))!=0)
{
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine("Received: {0}", data);
data = data.ToUpper();
byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
// 回传数据
stream.Write(msg, 0, msg.Length);
Console.WriteLine("Sent: {0}", data);
}
// 关闭连接
client.Close();
}
}
catch (SocketException e) {
Console.WriteLine("SocketException: {0}", e);
}
finally {
// 停止监听
server.Stop();
}
Console.WriteLine("\nHit enter to continue...");
Console.Read();
}
}
以上就是C#网络编程中常用特性介绍的完整攻略,包含了Socket、WebClient、HttpWebRequest、TcpListener等常用特性的用法和示例。希望可以帮助到大家在网络编程过程中的理解和使用。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:C#网络编程中常用特性介绍 - Python技术站