Socket 异步通信

时间:2023-03-08 22:30:03
Socket 异步通信
最近在写数据通信的时候用到的东西!希望对大家有帮助
         /// <summary>
/// 获取或设置服务器IP地址
/// </summary>
public string serverIP = "";
/// <summary>
/// 获取或设置服务器端口
/// </summary>
public int serverPort = ;
/// <summary>
/// 连接对象
/// </summary>
private Socket conn = null;
/// <summary>
/// 监听连接对象
/// </summary>
private Socket listenSocket = null;
/// <summary>
/// 是否停止收发数据(true:停止收发;false:可以收发)
/// </summary>
private volatile bool stopFlag = true;
/// <summary>
/// 是否连接已断开(true:已断开;false:已连接)
/// </summary>
public volatile bool isSocketBroken = true;
private ManualResetEvent allDone = new ManualResetEvent(false);
/// <summary>
/// 抛出接收到的数据的事件
/// </summary>
public event NetInfoEventHandler.InfoEvent infoEvent;
/// <summary>
/// 抛出异常处理的事件
/// </summary>
public event ExceptionEventHandler.ExceptionEvent exceptionEvent; /// <summary>
/// 可以重连的次数,默认不重连
/// </summary>
public int canReconnectNum = ;
/// <summary>
/// 已经重连的次数
/// </summary>
public int ReconnectedNum = ; /// <summary>
/// 连接成功编码
/// </summary>
public static string SUCCESS_CONNECT = "SUCCESS";
/// <summary>
/// 连接异常编码
/// </summary>
public static string EXCEPTION_CONNECT = "CONNECT";
/// <summary>
/// 接收异常编码
/// </summary>
public static string EXCEPTION_RECEIVE = "RECEIVE";
/// <summary>
/// 发送异常编码
/// </summary>
public static string EXCEPTION_SEND = "SEND";
/// <summary>
/// 数据内容起始位置
/// </summary>
public static int GOOD_PARSER_OFFSET = ; /// <summary>
/// 写异常log的对象
/// </summary>
public WriteLog exceptionMsgLog;
/// <summary>
/// 最新接收到的数据
/// </summary>
public byte[] read;
/// <summary>
/// 最新发送的数据
/// </summary>
public byte[] write;
/// <summary>
/// 接收数据的任务
/// </summary>
private Task receiveDataTask;
/// <summary>
///监听连接的任务
/// </summary>
private Task lisenerTask;
/// <summary>
/// 数据开始标志
/// </summary>
private char DataBeginChar = '{';
/// <summary>
/// 数据结束标志
/// </summary>
private char DataEndChar = '}';
/// <summary>
/// 存放不完整的数据
/// </summary>
public byte[] totalReadByte;
public Socket workSocket = null; public Connection()
{
} /// <summary>
/// 构造函数
/// </summary>
/// <param name="serverIp"></param>
/// <param name="serverPort"></param>
/// <param name="errorLog"></param>
public Connection(string serverIp,int serverPort,WriteLog errorLog)
{
this.serverIP = serverIp;
this.serverPort = serverPort;
this.exceptionMsgLog = errorLog;
} /// <summary>
/// 构造函数
/// </summary>
/// <param name="serverIp"></param>
/// <param name="serverPort"></param>
/// <param name="errorLog"></param>
public Connection(string serverIp, int serverPort,int receiveBufferSize,int sendBufferSize, WriteLog errorLog)
{
this.serverIP = serverIp;
this.serverPort = serverPort;
this.exceptionMsgLog = errorLog;
this.read = new byte[receiveBufferSize];
this.write = new byte[sendBufferSize];
} /// <summary>
/// 建立连接
/// </summary>
/// <returns></returns>
public bool connect()
{
bool ret = false; try
{
//初始化
this.conn = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//开始连接
this.conn.Connect(this.serverIP, this.serverPort);
//连接成功,状态设置成已连接
this.isSocketBroken = false;
//开始接收数据
this.stopFlag = false;
if (this.read == null)
{
this.read = new byte[this.conn.ReceiveBufferSize];
}
if (this.write == null)
{
this.write = new byte[this.conn.SendBufferSize];
}
//异步接收数据
SocketError socketErr;
this.conn.BeginReceive(this.read, , this.read.Length, SocketFlags.None, out socketErr, new AsyncCallback(ReadCallback), this);
//启动后台任务同步接收数据
//this.receiveDataTask = new Task(() => this.syncReceive(this.conn, 0));
//this.receiveDataTask.Start();
//allDone.Set(); //连接处理成功
onConnectSuccess();
ret = true;
}
catch (Exception ex)
{
if (this.exceptionMsgLog != null)
{
this.exceptionMsgLog.log(LogLevel.SYSTEMERROR, ex.TargetSite + ex.Message + ex.StackTrace + ex.ToString());
}
onConnectException(ex.TargetSite + ex.Message + ex.StackTrace + ex.ToString(),EXCEPTION_CONNECT);
} return ret;
} /// <summary>
/// 连接成功的处理
/// </summary>
private void onConnectSuccess()
{
try
{
//把收到的对象转发给外面的事件
if (this.exceptionEvent != null)
{
exceptionEvent(this, new ExceptionEventHandler("", SUCCESS_CONNECT));
}
//重连次数清零
this.ReconnectedNum = ;
}
catch (Exception ex)
{
if (this.exceptionMsgLog != null)
{
this.exceptionMsgLog.log(LogLevel.SYSTEMERROR, ex.TargetSite + ex.Message + ex.StackTrace + ex.ToString());
}
}
} /// <summary>
/// 连接出现异常的处理
/// </summary>
private void onConnectException(string exceptionInfo,string exceptionCode)
{
try
{
//把收到的对象转发给外面的事件
if (this.exceptionEvent != null)
{
exceptionEvent(this, new ExceptionEventHandler(exceptionInfo, exceptionCode));
}
//是否要重连
if (this.canReconnectNum > )
{
if (this.ReconnectedNum < this.canReconnectNum)
{
this.ReconnectedNum++;
if (this.conn != null)
{
this.disconnect();
}
this.connect();
}
}
else
{
this.isSocketBroken = true;
if (this.conn != null)
{
this.disconnect();
}
}
}
catch (Exception ex)
{
if (this.exceptionMsgLog != null)
{
this.exceptionMsgLog.log(LogLevel.SYSTEMERROR, ex.TargetSite + ex.Message + ex.StackTrace + ex.ToString());
}
}
} /// <summary>
/// 接收数据出现异常的处理
/// </summary>
private void onReceiveException(string exceptionInfo, string exceptionCode)
{
try
{
onConnectException(exceptionInfo, exceptionCode);
}
catch (Exception ex)
{
if (this.exceptionMsgLog != null)
{
this.exceptionMsgLog.log(LogLevel.SYSTEMERROR, ex.TargetSite + ex.Message + ex.StackTrace + ex.ToString());
}
}
} /// <summary>
/// 发送数据出现异常的处理
/// </summary>
private void onSendException(string exceptionInfo, string exceptionCode)
{
try
{
onConnectException(exceptionInfo, exceptionCode);
}
catch (Exception ex)
{
if (this.exceptionMsgLog != null)
{
this.exceptionMsgLog.log(LogLevel.SYSTEMERROR, ex.TargetSite + ex.Message + ex.StackTrace + ex.ToString());
}
}
} /// <summary>
/// 建立连接
/// </summary>
/// <returns></returns>
public bool lisenter()
{
bool ret = false; try
{
IPEndPoint ipe = new IPEndPoint(IPAddress.Parse(this.serverIP), this.serverPort);
this.conn = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
this.conn.Bind(ipe);
//监听成功,状态设置成已连接
this.isSocketBroken = false;
//开始接收数据
this.stopFlag = false;
if (this.read == null)
{
this.read = new byte[this.conn.ReceiveBufferSize];
}
if (this.write == null)
{
this.write = new byte[this.conn.SendBufferSize];
}
//启动后台任务监听连接
this.lisenerTask = new Task(() => this.startListen());
this.lisenerTask.Start();
allDone.Set(); //连接处理成功
ret = true;
}
catch (Exception ex)
{
if (this.exceptionMsgLog != null)
{
this.exceptionMsgLog.log(LogLevel.SYSTEMERROR, ex.TargetSite + ex.Message + ex.StackTrace + ex.ToString());
}
onConnectException(ex.TargetSite + ex.Message + ex.StackTrace + ex.ToString(), EXCEPTION_CONNECT);
} return ret;
} private void startListen()
{
try
{
conn.Listen(); while (!stopFlag)
{
allDone.Reset(); // Start an asynchronous socket to listen for connections.
//Console.WriteLine("Waiting for a connection...");
try
{
conn.BeginAccept(new AsyncCallback(AcceptCallback), conn);
}
catch (Exception e)
{
//Console.WriteLine(e.ToString());
} // Wait until a connection is made before continuing.
allDone.WaitOne();
}
}
catch (Exception ex)
{
if (this.exceptionMsgLog != null)
{
this.exceptionMsgLog.log(LogLevel.SYSTEMERROR, ex.TargetSite + ex.Message + ex.StackTrace + ex.ToString());
}
onConnectException(ex.TargetSite + ex.Message + ex.StackTrace + ex.ToString(), EXCEPTION_CONNECT);
}
} class ReadSocketState
{
public Socket socket;
public volatile bool isStopFlag;
}
private ReadSocketState rss = null;
public const int DATA_OFFSET = ;
public void AcceptCallback(IAsyncResult ar)
{
try
{
Socket listenSocket = (Socket)ar.AsyncState;
Socket tempSocket = listenSocket.EndAccept(ar); // Signal the main thread to continue.
allDone.Set(); Connection newConn = new Connection(listenSocket.AddressFamily.ToString(),,this.exceptionMsgLog);
newConn.conn = tempSocket;
newConn.read = new byte[tempSocket.ReceiveBufferSize];
newConn.write = new byte[tempSocket.SendBufferSize];
newConn.isSocketBroken = false;
newConn.infoEvent += new NetInfoEventHandler.InfoEvent(ClientSocket_infoEvent);
newConn.exceptionEvent += new ExceptionEventHandler.ExceptionEvent(ClientSocket_ExceptionEvent);
//异步接收数据
SocketError socketErr;
newConn.conn.BeginReceive(newConn.read, , newConn.read.Length, SocketFlags.None, out socketErr, new AsyncCallback(ReadCallback), newConn);
////启动后台任务同步接收数据
//Task newTask = new Task(() => newConn.syncReceive(newConn.conn, 0));
//newTask.Start();
//newConn.allDone.Set();
//通知有一个连接连上来了
if (this.exceptionEvent != null)
{
exceptionEvent(newConn, new ExceptionEventHandler("客户端有新的客户连进来了", SUCCESS_CONNECT));
} //ThreadPool.QueueUserWorkItem(new WaitCallback(syncReceive), rss);
}
catch (Exception ex)
{
if (this.exceptionMsgLog != null)
{
this.exceptionMsgLog.log(LogLevel.SYSTEMERROR, ex.TargetSite + ex.Message + ex.StackTrace + ex.ToString());
}
onConnectException(ex.TargetSite + ex.Message + ex.StackTrace + ex.ToString(), EXCEPTION_CONNECT);
} } public void ReadCallback(IAsyncResult ar)
{
Connection con = null;
try
{
con = (Connection)ar.AsyncState;
Socket socket = con.conn;
// Read data from the remote device.
SocketError socketErr;
int bytesRead = socket.EndReceive(ar, out socketErr); string temp = Encoding.UTF8.GetString(con.read);
if ( == bytesRead)
{
//errorLogger.log(ZDLogger.LVL_CRITCAL, CLASS_NM, "syncReceive", "Connection is broken!");
//throw new SocketException(System.Convert.ToInt32(SocketError.ConnectionReset));
}
else
{
if (temp.IndexOf("MARKET") < && temp.IndexOf("TEST") < )
{
this.exceptionMsgLog.log(LogLevel.SYSTEMERROR, temp);
}
string tmp = con.analyzeData(bytesRead, con); //if (tmp.IndexOf("MARKET") < 0)
//{
// this.exceptionMsgLog.log(LogLevel.SYSTEMERROR, tmp);
//} //转为后台线程处理读取的数据,不阻塞主线程对数据的读取
if (!string.IsNullOrEmpty(tmp))
{
this.exceptionMsgLog.log(LogLevel.SYSTEMERROR, "启动任务前");
Task task = new Task(() => do_OneReceiveData(tmp, con));
task.Start();
this.exceptionMsgLog.log(LogLevel.SYSTEMERROR, "启动任务后");
}
} //异步接收数据
//SocketError socketErr;
con.conn.BeginReceive(con.read, , con.read.Length, SocketFlags.None, out socketErr, new AsyncCallback(ReadCallback), con); }
catch (SocketException se)
{
if (this.exceptionMsgLog != null)
{
this.exceptionMsgLog.log(LogLevel.SYSTEMERROR, se.StackTrace);
}
if (con != null)
{
con.onReceiveException(se.StackTrace, EXCEPTION_RECEIVE);
}
}
catch (Exception ex)
{
if (this.exceptionMsgLog != null)
{
this.exceptionMsgLog.log(LogLevel.SYSTEMERROR, ex.TargetSite + ex.Message + ex.StackTrace + ex.ToString());
}
if (con != null)
{
con.onReceiveException(ex.TargetSite + ex.Message + ex.StackTrace + ex.ToString(), EXCEPTION_RECEIVE);
}
}
} /// <summary>
/// 接收到客户端一条数据的处理
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ClientSocket_infoEvent(Connection sender, NetInfoEventHandler e)
{
try
{
NetInfo netInfo = e.EventArg;
//心跳数据不处理
if (netInfo.code == CommandCode.HEARTBIT)
{
return;
}
if (this.infoEvent != null)
{
infoEvent(sender, new NetInfoEventHandler(netInfo));
} }
catch (Exception ex)
{
this.exceptionMsgLog.log(LogLevel.SYSTEMERROR, ex.TargetSite + ex.Message + ex.StackTrace + ex.ToString());
}
} /// <summary>
/// 接收到客户端异常的处理
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ClientSocket_ExceptionEvent(Connection sender, ExceptionEventHandler e)
{
try
{
string code = e.EventCode;
string msg = e.EventArg;
//把收到的对象转发给外面的事件
if (this.exceptionEvent != null)
{
exceptionEvent(sender, new ExceptionEventHandler(msg, code));
} }
catch (Exception ex)
{
this.exceptionMsgLog.log(LogLevel.SYSTEMERROR, ex.TargetSite + ex.Message + ex.StackTrace + ex.ToString());
}
} public void syncReceive(object stateObj)
{
//ReadSocketState rss = (ReadSocketState)stateObj;
//Socket socket = rss.socket;
//try
//{
// DateTime timeBegin = DateTime.Now; // while (true)
// {
// if (socket == null || this.isSocketBroken)
// {
// continue;
// } // //NetInfo netInfo = readClientRequestMsg(socket, 5000); // if (socket.Poll(3000000, SelectMode.SelectRead)) // one-second timeout
// {
// int bytesRead = socket.Receive(this.read);
// //string temp = Encoding.UTF8.GetString(networkState.readBuffer);
// if (0 == bytesRead)
// {
// //errorLogger.log(ZDLogger.LVL_CRITCAL, CLASS_NM, "syncReceive", "Connection is broken!");
// throw new SocketException(System.Convert.ToInt32(SocketError.ConnectionReset));
// }
// string tmp = this.analyzeData(bytesRead); // //转为后台线程处理读取的数据,不阻塞主线程对数据的读取
// if (!string.IsNullOrEmpty(tmp))
// {
// Task task = new Task(() => this.do_OneReceiveClientData(tmp, socket));
// task.Start();
// }
// } // if (rss.isStopFlag)
// {
// socket.Close();
// break;
// }
// }
//}
//catch (System.ObjectDisposedException ode)
//{
// // this exception means socket_ is already closed when poll() is called
// Console.WriteLine(ode.ToString());
//}
//catch (Exception ex)
//{
// if (this.exceptionMsgLog != null)
// {
// this.exceptionMsgLog.log(LogLevel.SYSTEMERROR, ex.TargetSite + ex.Message + ex.StackTrace + ex.ToString());
// }
// onConnectException(ex.TargetSite + ex.Message + ex.StackTrace + ex.ToString(), EXCEPTION_CONNECT);
//} } public NetInfo readClientRequestMsg(Socket socket, int timeout)
{
try
{
byte[] data = syncReceive(socket, timeout);
// Timeout
if (data == null) return null; string msg = System.Text.ASCIIEncoding.ASCII.GetString(data, GOOD_PARSER_OFFSET, data.Length - GOOD_PARSER_OFFSET); //errorLogger.log(ZDLogger.LVL_CRITCAL, msg); NetInfo netInfo = new NetInfo();
netInfo.MyReadString(msg);
return netInfo;
}
catch (Exception ex)
{
if (this.exceptionMsgLog != null)
{
this.exceptionMsgLog.log(LogLevel.SYSTEMERROR, ex.TargetSite + ex.Message + ex.StackTrace + ex.ToString());
}
onConnectException(ex.TargetSite + ex.Message + ex.StackTrace + ex.ToString(), EXCEPTION_CONNECT);
return null;
} } /// <summary>
/// 断开连接
/// </summary>
/// <returns></returns>
public bool disconnect()
{
bool ret = false; try
{
//this.conn.Close();
this.conn.Disconnect(true);
//连接断开成功,状态设置成已断开
this.isSocketBroken = true;
this.stopFlag = true;
if (this.receiveDataTask != null)
{
this.receiveDataTask.Dispose();
this.receiveDataTask = null;
}
if (this.lisenerTask != null)
{
this.lisenerTask.Dispose();
this.lisenerTask = null;
}
allDone.Set(); //连接断开处理成功
ret = true;
}
catch (Exception ex)
{
if (this.exceptionMsgLog != null)
{
this.exceptionMsgLog.log(LogLevel.SYSTEMERROR, ex.TargetSite + ex.Message + ex.StackTrace + ex.ToString());
}
onConnectException(ex.TargetSite + ex.Message + ex.StackTrace + ex.ToString(), EXCEPTION_CONNECT);
} return ret;
} /// <summary>
/// 同步接收数据(后台任务处理)
/// </summary>
/// <param name="socket"></param>
/// <param name="timeout"></param>
/// <returns></returns>
private byte[] syncReceive(Socket socket, int timeout)
{
try
{
DateTime timeBegin = DateTime.Now;
while (true)
{
if (socket == null || this.isSocketBroken)
{
continue;
} if (socket.Poll(, SelectMode.SelectRead)) // one-second timeout
{
int bytesRead = socket.Receive(this.read);
string temp = Encoding.UTF8.GetString(this.read);
if ( == bytesRead)
{
//errorLogger.log(ZDLogger.LVL_CRITCAL, CLASS_NM, "syncReceive", "Connection is broken!");
throw new SocketException(System.Convert.ToInt32(SocketError.ConnectionReset));
}
if (temp.IndexOf("MARKET") < )
{
this.exceptionMsgLog.log(LogLevel.SYSTEMERROR, temp);
}
string tmp = this.analyzeData(bytesRead,this); //if (tmp.IndexOf("MARKET") < 0)
//{
// this.exceptionMsgLog.log(LogLevel.SYSTEMERROR, tmp);
//} //转为后台线程处理读取的数据,不阻塞主线程对数据的读取
if (!string.IsNullOrEmpty(tmp))
{
Task task = new Task(() => do_OneReceiveData(tmp,this));
task.Start();
}
}
else
{
//超时的话退出
//if (timeout != 0 && DateTime.Now.Subtract(timeBegin).TotalMilliseconds > timeout)
//break;
}
}
}
catch (System.ObjectDisposedException ode)
{
if (this.exceptionMsgLog != null)
{
this.exceptionMsgLog.log(LogLevel.SYSTEMERROR, ode.StackTrace);
}
this.onReceiveException(ode.StackTrace, EXCEPTION_RECEIVE);
}
catch (Exception ex)
{
if (this.exceptionMsgLog != null)
{
this.exceptionMsgLog.log(LogLevel.SYSTEMERROR, ex.TargetSite + ex.Message + ex.StackTrace + ex.ToString());
}
this.onReceiveException(ex.TargetSite + ex.Message + ex.StackTrace + ex.ToString(), EXCEPTION_RECEIVE);
} return null;
} /// <summary>
/// 处理接收到的完整对象数据
/// </summary>
/// <param name="inPut"></param>
private void do_OneReceiveData(string inPut,Connection conn)
{
try
{
int fir = inPut.IndexOf('{');
int sec = inPut.IndexOf('}');
while (fir != - && sec != -)
{
string obj = inPut.Substring(fir + , sec - fir - );
inPut = inPut.Substring(sec + );//删除前面完整对象的字符串
//===========================//处理obj
fir = obj.IndexOf('(');
sec = obj.IndexOf(')');
string lenstr = obj.Substring(fir + , sec - );
lenstr = lenstr.Substring();
int len = int.Parse(lenstr);
obj = obj.Substring(sec + );//取完整对象的值
if (len == obj.Length) //完整正确的对象
{
NetInfo netInfo = new NetInfo();
netInfo.MyReadString(obj);
//把收到的对象转发给外面的事件
if (infoEvent != null)
{
conn.infoEvent(conn, new NetInfoEventHandler(netInfo));
}
}
fir = inPut.IndexOf('{');
sec = inPut.IndexOf('}');
}
}
catch (Exception ex)
{
if (this.exceptionMsgLog != null)
{
this.exceptionMsgLog.log(LogLevel.SYSTEMERROR, ex.TargetSite + ex.Message + ex.StackTrace + ex.ToString());
}
}
} /// <summary>
/// 处理接收到客户端请求的完整对象数据
/// </summary>
/// <param name="inPut"></param>
private void do_OneReceiveClientData(string inPut,Connection socket)
{
try
{
int fir = inPut.IndexOf('{');
int sec = inPut.IndexOf('}');
while (fir != - && sec != -)
{
string obj = inPut.Substring(fir + , sec - fir - );
inPut = inPut.Substring(sec + );//删除前面完整对象的字符串
//===========================//处理obj
fir = obj.IndexOf('(');
sec = obj.IndexOf(')');
string lenstr = obj.Substring(fir + , sec - );
lenstr = lenstr.Substring();
int len = int.Parse(lenstr);
obj = obj.Substring(sec + );//取完整对象的值
if (len == obj.Length) //完整正确的对象
{
NetInfo netInfo = new NetInfo();
netInfo.MyReadString(obj);
//把收到的对象转发给外面的事件
if (infoEvent != null)
{
infoEvent(socket, new NetInfoEventHandler(netInfo));
}
}
fir = inPut.IndexOf('{');
sec = inPut.IndexOf('}');
}
}
catch (Exception ex)
{
if (this.exceptionMsgLog != null)
{
this.exceptionMsgLog.log(LogLevel.SYSTEMERROR, ex.TargetSite + ex.Message + ex.StackTrace + ex.ToString());
}
}
} /// <summary>
/// 解析当前接收的数据块,并将完整的数据返回(没有完整数据返回空)
/// </summary>
/// <param name="len"></param>
/// <returns></returns>
public string analyzeData(int len,Connection con)
{
try
{
byte[] bytes = new byte[len];
List<byte> list = con.read.ToList();
//移除无效部分
list.RemoveRange(len, list.Count - len); bytes = list.ToArray<byte>().Clone() as byte[]; Boolean begin = false;
string inPut = Encoding.UTF8.GetString(bytes);
Boolean end = inPut.EndsWith(con.DataEndChar.ToString());
if (inPut.ElementAt() == con.DataBeginChar)
{
begin = true;
} if (begin && end)
{
//addByteToTotal(bytes);
return inPut;
}
else if (end) //处理最后的信息
{ addByteToTotal(bytes);
inPut = Encoding.UTF8.GetString(totalReadByte);
totalReadByte = null;
return inPut;
}
else //中间的
{
addByteToTotal(bytes);
inPut = Encoding.UTF8.GetString(totalReadByte);
int tEnd = inPut.LastIndexOf(con.DataEndChar);
string r = "";
string l = "";
if (tEnd >= )
{
r = inPut.Substring(, tEnd + );
l = inPut.Substring(tEnd + );
if (l.Length > )
{
totalReadByte = Encoding.UTF8.GetBytes(l);
}
}
return r;
}
}
catch(Exception ex)
{
if (this.exceptionMsgLog != null)
{
this.exceptionMsgLog.log(LogLevel.SYSTEMERROR, ex.TargetSite + ex.Message + ex.StackTrace + ex.ToString());
}
this.onReceiveException(ex.TargetSite + ex.Message + ex.StackTrace + ex.ToString(), EXCEPTION_RECEIVE);
return "";
}
} /// <summary>
/// 增加一个新读取的字节数组数据到总的字节数组数据中
/// </summary>
/// <param name="bytes"></param>
public void addByteToTotal(byte[] bytes)
{
if (bytes == null) return;
try
{
lock (this)
{
//用来存放原来残余的数据
byte[] oldData = null;
//用来计算残余数据的长度
int Count = ;
if (totalReadByte != null)
{
Count = totalReadByte.Length;
} if (Count != )
{
oldData = (byte[])totalReadByte.Clone();
}
totalReadByte = new byte[Count + bytes.Length];
if (Count > )
{
oldData.CopyTo(totalReadByte, );
}
bytes.CopyTo(totalReadByte, Count);
}
}
catch (Exception ex)
{
if (this.exceptionMsgLog != null)
{
this.exceptionMsgLog.log(LogLevel.SYSTEMERROR, ex.TargetSite + ex.Message + ex.StackTrace + ex.ToString());
}
this.onReceiveException(ex.TargetSite + ex.Message + ex.StackTrace + ex.ToString(), EXCEPTION_RECEIVE);
}
} /// <summary>
/// 发送netinfo数据
/// </summary>
/// <param name="obj"></param>
public void sendNetInfo(NetInfo obj)
{
try
{
this.sendMsg(CommonFunction.ObjectStringToBytes(obj.MyToString()));
}
catch (Exception ex)
{
if (this.exceptionMsgLog != null)
{
this.exceptionMsgLog.log(LogLevel.SYSTEMERROR, ex.TargetSite + ex.Message + ex.StackTrace + ex.ToString());
}
this.onSendException(ex.TargetSite + ex.Message + ex.StackTrace + ex.ToString(), EXCEPTION_SEND);
}
} /// <summary>
/// 发送数据
/// </summary>
/// <param name="data"></param>
public void sendMsg(byte[] data)
{
try
{
lock (this.conn)
{
int offset = ;
int size = data.Length;
size += offset;
while (offset < size)
{
int count = this.conn.Send(data, offset, size - offset, SocketFlags.None);
offset += count;
}
}
}
catch (Exception ex)
{
if (this.exceptionMsgLog != null)
{
this.exceptionMsgLog.log(LogLevel.SYSTEMERROR, ex.TargetSite + ex.Message + ex.StackTrace + ex.ToString());
}
this.onSendException(ex.TargetSite + ex.Message + ex.StackTrace + ex.ToString(), EXCEPTION_SEND);
}
} /// <summary>
/// 接收到一个完整数据的处理,在调用的类中实现这个方法来实现各自的处理逻辑
/// </summary>
/// <param name="rawMsg"></param>
//public abstract void onReceiveData(string data); /// <summary>
/// 接收到一个监听连接发来的完整数据的处理,在调用的类中实现这个方法来实现各自的处理逻辑
/// </summary>
/// <param name="rawMsg"></param>
//public abstract void onReceiveClientData(string data, Socket socket); ///// <summary>
///// 接收数据出现异常的处理,在调用的类中实现这个方法来实现各自的处理逻辑
///// </summary>
///// <param name="rawMsg"></param>
//public abstract void onReceiveDataException(); ///// <summary>
///// 发送数据出现异常的处理,在调用的类中实现这个方法来实现各自的处理逻辑
///// </summary>
///// <param name="rawMsg"></param>
//public abstract void onSendDataException();
///// <summary>
///// 建立连接出现异常的处理,在调用的类中实现这个方法来实现各自的处理逻辑
///// </summary>
///// <param name="rawMsg"></param>
//public abstract void onConnectException();