c# socket编程框架
时间: 2023-08-24 15:08:16 浏览: 285
C#的Socket 开发框架
在C#中,使用Socket类可以进行Socket编程,进行网络通信。下面是一个基本的C# Socket编程框架示例:
```csharp
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class SocketFramework
{
private Socket serverSocket;
private Socket clientSocket;
private byte[] buffer;
public void StartServer(string ipAddress, int port)
{
try
{
// 创建服务器Socket
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// 绑定IP地址和端口号
IPAddress ip = IPAddress.Parse(ipAddress);
IPEndPoint ipEndPoint = new IPEndPoint(ip, port);
serverSocket.Bind(ipEndPoint);
// 监听客户端连接请求
serverSocket.Listen(10);
Console.WriteLine("Server started. Waiting for client connection...");
// 接受客户端连接
clientSocket = serverSocket.Accept();
Console.WriteLine("Client connected.");
// 开始接收消息
buffer = new byte[1024];
clientSocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), null);
}
catch (Exception e)
{
Console.WriteLine("Error: " + e.Message);
}
}
public void ConnectToServer(string ipAddress, int port)
{
try
{
// 创建客户端Socket
clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// 连接服务器
IPAddress ip = IPAddress.Parse(ipAddress);
IPEndPoint ipEndPoint = new IPEndPoint(ip, port);
clientSocket.Connect(ipEndPoint);
Console.WriteLine("Connected to server.");
// 开始接收消息
buffer = new byte[1024];
clientSocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), null);
}
catch (Exception e)
{
Console.WriteLine("Error: " + e.Message);
}
}
private void ReceiveCallback(IAsyncResult ar)
{
try
{
// 接收消息并处理
int receivedBytes = clientSocket.EndReceive(ar);
string message = Encoding.ASCII.GetString(buffer, 0, receivedBytes);
Console.WriteLine("Received message: " + message);
// 继续接收消息
buffer = new byte[1024];
clientSocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), null);
}
catch (Exception e)
{
Console.WriteLine("Error: " + e.Message);
}
}
public void SendMessage(string message)
{
try
{
// 发送消息给服务器或客户端
byte[] data = Encoding.ASCII.GetBytes(message);
clientSocket.Send(data);
Console.WriteLine("Sent message: " + message);
}
catch (Exception e)
{
Console.WriteLine("Error: " + e.Message);
}
}
public void CloseConnection()
{
// 关闭连接
clientSocket.Close();
serverSocket.Close();
Console.WriteLine("Connection closed.");
}
}
```
这个框架示例包含了一个`SocketFramework`类,其中包括了服务器端和客户端的基本操作。你可以使用`StartServer()`方法启动一个服务器,监听客户端连接;使用`ConnectToServer()`方法连接到一个服务器;使用`SendMessage()`方法发送消息给对方;使用`CloseConnection()`方法关闭连接。
需要注意的是,这只是一个基本的Socket编程框架示例,你可以根据自己的实际需求进行扩展和完善。同时,Socket编程涉及到网络通信的复杂性,还需要处理错误和异常情况,确保代码的健壮性和稳定性。
希望对你有所帮助!
阅读全文