引言随着互联网技术的飞速发展,网络编程已经成为软件开发中的一个重要领域。C作为一种强大的编程语言,在网络编程方面具有广泛的应用。本文将深入探讨C网络编程,重点关注主流通信协议的实战技巧,帮助读者轻松掌...
随着互联网技术的飞速发展,网络编程已经成为软件开发中的一个重要领域。C#作为一种强大的编程语言,在网络编程方面具有广泛的应用。本文将深入探讨C#网络编程,重点关注主流通信协议的实战技巧,帮助读者轻松掌握网络编程的核心知识。
网络编程是指利用编程语言实现计算机之间数据传输的技术。在C#中,网络编程主要依赖于System.Net和System.Net.Sockets命名空间下的类库。
TCP(传输控制协议)是一种面向连接的、可靠的、基于字节流的传输层通信协议。
using System.Net.Sockets;
public void StartClient(string ip, int port)
{ Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Parse(ip), port); try { clientSocket.Connect(localEndPoint); Console.WriteLine("连接成功"); // 发送数据 string message = "Hello, Server!"; byte[] byteData = System.Text.Encoding.ASCII.GetBytes(message); clientSocket.Send(byteData); // 接收数据 byte[] byteReceive = new byte[1024]; int bytesRec = clientSocket.Receive(byteReceive); string dataReceived = System.Text.Encoding.ASCII.GetString(byteReceive, 0, bytesRec); Console.WriteLine("接收到的数据:" + dataReceived); clientSocket.Shutdown(SocketShutdown.Both); clientSocket.Close(); } catch (Exception e) { Console.WriteLine("发生错误:" + e.ToString()); }
}using System.Net.Sockets;
using System.Text;
public void StartServer(string ip, int port)
{ Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Parse(ip), port); try { listener.Bind(localEndPoint); listener.Listen(10); Console.WriteLine("等待连接..."); while (true) { Socket handler = listener.Accept(); Console.WriteLine("连接成功"); // 接收数据 byte[] byteReceive = new byte[1024]; int bytesRec = handler.Receive(byteReceive); string dataReceived = Encoding.ASCII.GetString(byteReceive, 0, bytesRec); Console.WriteLine("接收到的数据:" + dataReceived); // 发送数据 string message = "Hello, Client!"; byte[] byteData = Encoding.ASCII.GetBytes(message); handler.Send(byteData); handler.Shutdown(SocketShutdown.Both); handler.Close(); } } catch (Exception e) { Console.WriteLine("发生错误:" + e.ToString()); }
}UDP(用户数据报协议)是一种无连接的、不可靠的、基于数据报的传输层通信协议。
using System.Net.Sockets;
using System.Text;
public void StartUdpClient(string ip, int port)
{ UdpClient udpClient = new UdpClient(); IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Parse(ip), port); try { byte[] sendBytes = Encoding.ASCII.GetBytes("Hello, Server!"); udpClient.Send(sendBytes, sendBytes.Length, remoteEndPoint); byte[] receiveBytes = udpClient.Receive(ref remoteEndPoint); string dataReceived = Encoding.ASCII.GetString(receiveBytes); Console.WriteLine("接收到的数据:" + dataReceived); } catch (Exception e) { Console.WriteLine("发生错误:" + e.ToString()); }
}using System.Net.Sockets;
using System.Text;
public void StartUdpServer(int port)
{ UdpListener udpListener = new UdpListener(port); IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, port); try { udpListener.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); udpListener.Bind(localEndPoint); Console.WriteLine("等待连接..."); while (true) { UdpReceiveResult result = udpListener.Receive(); IPEndPoint remoteEndPoint = result.RemoteEndPoint; string dataReceived = Encoding.ASCII.GetString(result.Buffer); Console.WriteLine("接收到的数据:" + dataReceived); string message = "Hello, Client!"; byte[] sendBytes = Encoding.ASCII.GetBytes(message); udpListener.Send(sendBytes, sendBytes.Length, remoteEndPoint); } } catch (Exception e) { Console.WriteLine("发生错误:" + e.ToString()); }
}HTTP(超文本传输协议)是一种应用层协议,主要用于在Web浏览器和服务器之间传输超文本数据。
using System.Net.Http;
using System.Threading.Tasks;
public async Task GetHttpDataAsync(string url)
{ using (HttpClient client = new HttpClient()) { HttpResponseMessage response = await client.GetAsync(url); return await response.Content.ReadAsStringAsync(); }
} using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
public class HttpServer
{ private readonly HttpListener _listener; public HttpServer() { _listener = new HttpListener(); _listener.Prefixes.Add("http://localhost:8080/"); } public void Start() { _listener.Start(); _listener.BeginListen(null, ListenCallback); } private void ListenCallback(IAsyncResult result) { HttpListenerContext context = _listener.EndListen(result); HandleRequest(context); } private void HandleRequest(HttpListenerContext context) { string requestPath = context.Request.RawUrl; string response = "Hello, HTTP!"; byte[] buffer = Encoding.UTF8.GetBytes(response); context.Response.ContentLength64 = buffer.Length; context.Response.ContentType = "text/plain"; context.Response.OutputStream.Write(buffer, 0, buffer.Length); context.Response.OutputStream.Flush(); context.Response.Close(); } public void Stop() { _listener.Stop(); }
}本文深入探讨了C#网络编程,重点介绍了主流通信协议的实战技巧。通过学习本文,读者可以轻松掌握TCP、UDP和HTTP协议在网络编程中的应用,为后续开发高性能、高可靠的网络应用程序打下坚实基础。