引言随着互联网的普及,网络编程已经成为软件开发领域的重要技能之一。C作为.NET平台的主要编程语言,拥有强大的网络编程功能。本文将带您深入了解C网络编程,并通过实战案例解析,帮助您轻松入门网络应用开发...
随着互联网的普及,网络编程已经成为软件开发领域的重要技能之一。C#作为.NET平台的主要编程语言,拥有强大的网络编程功能。本文将带您深入了解C#网络编程,并通过实战案例解析,帮助您轻松入门网络应用开发。
网络编程是指利用计算机网络的通信协议,实现不同计算机之间数据传输的技术。C#网络编程主要基于TCP/IP协议,通过Socket进行数据传输。
C#网络编程主要分为两种模型:阻塞模型和非阻塞模型。
客户端-服务器模式是网络编程中最常见的模式。以下是一个简单的客户端-服务器聊天程序的实现:
服务器端代码:
using System;
using System.Net;
using System.Net.Sockets;
public class Server
{ private const int port = 12345; private static void Main(string[] args) { IPAddress ipAddr = IPAddress.Any; IPEndPoint localEndPoint = new IPEndPoint(ipAddr, port); Socket listener = new Socket(ipAddr.AddressFamily, SocketType.Stream, ProtocolType.Tcp); try { listener.Bind(localEndPoint); listener.Listen(10); Console.WriteLine("Waiting for a connection..."); Socket handler = listener.Accept(); Console.WriteLine("Connection accepted."); StateObject state = new StateObject(); state.workSocket = handler; IAsyncResult ar = handler.BeginReceive(state.buffer, 0, StateObject.bufferSize, 0, new AsyncCallback(ReadCallback), state); } catch (Exception e) { Console.WriteLine(e.ToString()); } Console.WriteLine("\nPress ENTER to continue..."); Console.Read(); } public static void ReadCallback(IAsyncResult ar) { StateObject state = (StateObject)ar.AsyncState; Socket handler = state.workSocket; int bytesRead = handler.EndReceive(ar); if (bytesRead > 0) { Console.WriteLine("Read {0} bytes from socket. \n Data: {1}", bytesRead, new string(state.buffer, 0, bytesRead)); IAsyncResult ar2 = handler.BeginSend(state.buffer, 0, bytesRead, 0, new AsyncCallback(SendCallback), handler); } } public static void SendCallback(IAsyncResult ar) { try { Socket handler = (Socket)ar.AsyncState; int bytesSent = handler.EndSend(ar); Console.WriteLine("Sent {0} bytes to client.", bytesSent); handler.Shutdown(SocketShutdown.Both); handler.Close(); } catch (Exception e) { Console.WriteLine(e.ToString()); } }
}
public class StateObject
{ public Socket workSocket = null; public const int bufferSize = 1024; public byte[] buffer = new byte[bufferSize];
}客户端代码:
using System;
using System.Net.Sockets;
using System.Text;
public class Client
{ private const string ip = "127.0.0.1"; private const int port = 12345; public static void Main(string[] args) { Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { IPEndPoint ie = new IPEndPoint(IPAddress.Parse(ip), port); client.Connect(ie); Console.WriteLine("Connected to server."); byte[] bytes = Encoding.ASCII.GetBytes("Hello, server!"); client.Send(bytes); byte[] buffer = new byte[1024]; int bytesRead = client.Receive(buffer); Console.WriteLine("Received from server: {0}", Encoding.ASCII.GetString(buffer, 0, bytesRead)); } catch (Exception e) { Console.WriteLine(e.ToString()); } client.Close(); }
}C#网络编程框架主要包括:
通过本文的介绍,相信您已经对C#网络编程有了初步的了解。通过实战案例,您可以更深入地掌握网络编程技巧。在实际开发中,可以根据需求选择合适的网络编程框架,提高开发效率。祝您在C#网络编程领域取得更好的成绩!