C#开发Socket客户端
我们先新建一个类:SocketClientAsync。
注意点:
1、由于Socket通讯是发送到缓存区内的数据是覆盖,而不是新的,也就是说如果我们第一次发送的内容是 byte[]{0x11,0x22};而第二次发送的内容是byte[]{0x22}。那么我们的服务端在第二次接受到的数据是byte[]{0x22,0x22}。
所以我们需要在(byte[] mes)方法里面声明
byte[] buffer = new byte[1024];
for (int i = 0; i < ; i++)
{
buffer[i] = 0x00;
}
起到的作用就是每次在发送新的内容到服务端的时候,会将所有的旧的内容替换掉;
2、关闭连接之前需要将通知服务端停止发送和接受,也就是
();
中断套接字连接:通知服务器端或客户端停止接收和发送数据。
通知完成之后如果客户端还连接着再进行自己的连接断开
if ()
{
();
}
3、具体类的代码见下图,可以直接使用
#region SocketClient客户端
public class SocketClientAsync
{
#region 声明变量
public string IPAdress;
public bool connected = false;
public Socket clientSocket;
private IPEndPoint hostEndPoint;
private int Flag = 0;
private AutoResetEvent autoConnectEvent = new AutoResetEvent(false);
private SocketAsyncEventArgs lisnterSocketAsyncEventArgs;
public delegate void StartListeHandler();
public event StartListeHandler StartListen;
public delegate void ReceiveMsgHandler(byte[] info, int i);
public event ReceiveMsgHandler OnMsgReceived;
private List<SocketAsyncEventArgs> s_lst = new List<SocketAsyncEventArgs>();
#endregion
#region 构造函数
/// <summary>
/// 构造函数
/// </summary>
/// <param name="hostName"></param>
/// <param name="port"></param>
/// <param name="i"></param>
public SocketClientAsync(string hostName, int port, int i)
{
Flag = i;
IPAdress = hostName;
IPAddress[] hostAddresses = (hostName);
= new IPEndPoint(hostAddresses[ - 1], port);
= new Socket(, , );
}
#endregion
#region 开始连接服务端
/// <summary>
/// 连接服务端
/// </summary>
/// <returns></returns>
private bool Connect()
{
using (SocketAsyncEventArgs args = new SocketAsyncEventArgs())
{
= ;
= ;
+= new EventHandler<SocketAsyncEventArgs>();
(args);
bool flag = (5000);
if ()
{
= new SocketAsyncEventArgs();
byte[] buffer = new byte[1024];
= ;
(buffer, 0, );
+= new EventHandler<SocketAsyncEventArgs>();
();
return true;
}
return false;
}
}
#endregion
#region 判断有没有连接上服务端
/// <summary>
/// 判断有没有连接上
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnConnect(object sender, SocketAsyncEventArgs e)
{
= ( == );
();
}
#endregion
#region 发送数据到服务端
/// <summary>
/// 发送
/// </summary>
/// <param name="mes"></param>
public void Send(byte[] mes)
{
if ()
{
EventHandler<SocketAsyncEventArgs> handler = null;
//byte[] buffer = (mes);
byte[] buffer = new byte[1024];
for (int i = 0; i < ; i++)
{
buffer[i] = 0x00;
}
(mes, 0, buffer, 0, );
SocketAsyncEventArgs senderSocketAsyncEventArgs = null;
lock (s_lst)
{
if (s_lst.Count > 0)
{
senderSocketAsyncEventArgs = s_lst[s_lst.Count - 1];
s_lst.RemoveAt(s_lst.Count - 1);
}
}
if (senderSocketAsyncEventArgs == null)
{
senderSocketAsyncEventArgs = new SocketAsyncEventArgs();
= ;
= ;
if (handler == null)
{
handler = delegate(object sender, SocketAsyncEventArgs _e)
{
lock (s_lst)
{
s_lst.Add(senderSocketAsyncEventArgs);
}
};
}
+= handler;
}
(buffer, 0, );
(senderSocketAsyncEventArgs);
}
else
{
= false;
}
}
#endregion
#region 监听服务端
/// <summary>
/// 监听服务端
/// </summary>
public void Listen()
{
if ( && != null)
{
try
{
( as Socket).ReceiveAsync(lisnterSocketAsyncEventArgs);
}
catch (Exception)
{
}
}
}
#endregion
#region 断开服务端的连接
/// <summary>
/// 断开连接
/// </summary>
/// <returns></returns>
private int Disconnect()
{
int res = 0;
try
{
();
}
catch (Exception)
{
}
try
{
();
}
catch (Exception)
{
}
= false;
return res;
}
#endregion
#region 数据接收
/// <summary>
/// 数据接受
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnReceive(object sender, SocketAsyncEventArgs e)
{
if ( == 0)
{
if ()
{
try
{
();
}
catch (Exception)
{
}
finally
{
if ()
{
();
}
}
}
byte[] info = new Byte[] { 0 };
(info, Flag);
}
else
{
byte[] buffer = new byte[];
(, 0, buffer, 0, );
(buffer, Flag);
Listen();
}
}
#endregion
#region 建立连接服务端的方法
/// <summary>
/// 建立连接的方法
/// </summary>
/// <returns></returns>
public bool ConnectServer()
{
bool flag = false;
+= new StartListeHandler(SocketClient_StartListen);
// += new ReceiveMsgHandler(SocketClient_OnMsgReceived);
flag = ();
if (!flag)
{
return flag;
}
return true;
}
#endregion
#region 关闭与服务端之间的连接
/// <summary>
/// 关闭连接的方法
/// </summary>
/// <returns></returns>
public int CloseLinkServer()
{
return ();
}
#endregion
#region 监听方法
/// <summary>
/// 监听的方法
/// </summary>
private void SocketClient_StartListen()
{
();
}
#endregion
#region IDispose member
public void Dispose()
{
if ()
{
();
}
}
#endregion
#region 析构函数
~SocketClientAsync()
{
try
{
if ()
{
();
}
}
catch
{
}
finally
{
}
}
#endregion
}
#endregion
4、然后就是类的调用了
//声明定义变量
private SocketClientAsync ClientLink;//客户端连接对象
private string Client_IP = "127.0.0.1";//服务端IP地址
private int Client_Port = 12345;//服务端监听的端口号
private Thread Client_Td;//通讯内部使用线程
private bool ClientLinkRes = false;//服务器通讯状态标志
private bool ThreadContinue = true;//线程轮询标志
private bool isOnline = false;//是否在线标志
/// <summary>
/// 启动线程
/// </summary>
private void StartServer()
{
Client_Td = new Thread(LinkSocketSerFunc);
Client_Td.Start();
}
/// <summary>
/// 重连服务端线程
/// </summary>
private void LinkSocketSerFunc()
{
object lockobj = new object();
int heartBeatCount = 0;
ClientLink = new SocketClientAsync(Client_IP, Client_Port, 0);
bool NotFirstIn = false;
while (ThreadContinue)
{
try
{
if (!ClientLinkRes)
{
isOnline = false;
if (NotFirstIn)
{
();
ClientLink = new SocketClientAsync(Client_IP, Client_Port, 0);
}
NotFirstIn = true;
+= new (Client_OnMsgReceived);//绑定接受到服务端消息的事件
ClientLinkRes = ();
}
else
{
//此处写通讯成功的逻辑处理
}
}
catch (Exception ex)
{
ClientLinkRes = false;
(());
}
(1000);
}
}
/// <summary>
/// 接收消息处理
/// </summary>
/// <param name="info"></param>
/// <param name="num"></param>
private void Client_OnMsgReceived(byte[] info, int num)
{
try
{
ClientHeartBeat = 0;
if ( > 0 && info[0] != 0)//BCR连接错误NO
{
//info为接受到服务器传过来的字节数组,需要进行什么样的逻辑处理在此书写便可
}
else
{
ClientLinkRes = false;
}
}
catch (Exception ex)
{
(());
}
}
/// <summary>
/// 终止服务
/// </summary>
public void StopServer()
{
if (ClientLinkRes)
{
ThreadContinue = false;
();
();
}
}
以上,基本的Socket客户端后台就写完了,可以直接复制使用,平时都是用这么去写Socket客户端,分享出来,以后大家就可以直接使用了,程序员要学会偷懒!!!