0
点赞
收藏
分享

微信扫一扫

c# socket 客户端异步实现


简易封装:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;

namespace dclient
{
public delegate void DelegateMsg(object msg);
public class Client
{
private static Socket _clientSocket;

private static string _server;
private static int _port;

public static DelegateMsg OnConnect;
public static DelegateMsg OnSend;
public static DelegateMsg OnReceive;
public static DelegateMsg OnServerDown;
public static DelegateMsg OnErr;

public static void Connect()
{
try
{
_server = System.Configuration.ConfigurationManager.AppSettings["serverIp"];
_port = int.Parse(System.Configuration.ConfigurationManager.AppSettings["serverPort"]);

IPEndPoint ip = new IPEndPoint(IPAddress.Parse(_server), _port);
_clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

_clientSocket.BeginConnect(ip, new AsyncCallback(ConnectCallBack), _clientSocket);
}
catch (Exception e)
{
throw e;
}
}

private static void ConnectCallBack(IAsyncResult iar)
{
Socket client = (Socket)iar.AsyncState;
try
{
client.EndConnect(iar);
OnConnect("已连接");
}
catch (SocketException e)
{
if (e.ErrorCode == 10061)
{
OnErr("服务器程序未运行或服务器端口未开放");
}
else
{
OnErr(e.Message);
}
}
finally
{
}
}

public static void Send(string msg)
{
if (_clientSocket == null || msg == string.Empty) return;

msg += "\r\n";

byte[] data = Encoding.UTF8.GetBytes(msg);
try
{
_clientSocket.BeginSend(data, 0, data.Length, SocketFlags.None, asyncResult =>
{
int length = _clientSocket.EndSend(asyncResult);
OnSend(string.Format("客户端发送消息:{0}", msg));
}, null);
}
catch (Exception e)
{
OnErr(e.Message);
}
}

public static void Recive()
{
byte[] data = new byte[1024];
try
{
_clientSocket.BeginReceive(data, 0, data.Length, SocketFlags.None,
asyncResult =>
{
try
{
int length = _clientSocket.EndReceive(asyncResult);
OnReceive(string.Format("收到服务器消息:长度:{1},{0}", Encoding.UTF8.GetString(data), length));
Recive();
}
catch (SocketException e)
{
if (e.ErrorCode == 10054)
{
OnServerDown("服务器已断线");
}
else
{
OnErr(e.Message);
}
}
}, null);
}
catch

使用:

public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Client.OnConnect += new DelegateMsg(connect);
Client.OnSend += new DelegateMsg(send);
Client.OnReceive += new DelegateMsg(receive);
Client.OnServerDown += new DelegateMsg(svrdown);
Client.OnErr += new DelegateMsg(onerr);
}

private void Form1_Load(object sender, EventArgs e)
{
Client.Connect();
}

private void connect(object msg)
{
System.Diagnostics.Debug.WriteLine(msg.ToString());
Client.Send("DALO 发送测试");
Client.Recive();
}

private void send(object msg)
{
System.Diagnostics.Debug.WriteLine(msg.ToString());
}

private void receive(object msg)
{
System.Diagnostics.Debug.WriteLine(msg.ToString());
}

private void svrdown(object msg)
{
System.Diagnostics.Debug.WriteLine(msg.ToString());
}

private void onerr(object

未实现的几个常用操作:
1、接收服务器发送的大数据量的合包。
2、服务器断线后客户端自动检测并重连,需先将_clientSocket释放。
3、心跳包。


举报

相关推荐

0 条评论