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();
Socket 异步通信的更多相关文章
- socket异步通信-如何设置成非阻塞模式、非阻塞模式下判断connect成功(失败)、判断recv/recvfrom成功(失败)、判断send/sendto
socket异步通信-如何设置成非阻塞模式.非阻塞模式下判断connect成功(失败).判断recv/recvfrom成功(失败).判断send/sendto 博客分类: Linux Socket s ...
- Socket异步通信学习三
接下来是客户端部分,采用同步接收模式,在SocketClient项目中新建了一个SynServer类,用于存放socket服务器代码,和AsynServer类似,主要有4个方法: 有一个全局socke ...
- Socket异步通信学习二
接下来是服务器部分,采用异步模式,新建了一个AsynServer类,用于存放socket服务器代码,主要有4个方法: 有一个全局socket,下面四个方法中都用到. Socket socket = n ...
- Socket异步通信学习一
最近在做一个频谱管理项目,负责通信模块,自己也是小白,重头学起,直至今天通信基本框架已经完成,把自己在学习中的心得与大家分享一下,做一个socket系列的博文,顺便加固一下自己对socket通信的认识 ...
- Socket异步通信及心跳包同时响应逻辑分析。
有段时间没有更博了,刚好最近在做Socket通信的项目,原理大致内容:[二维码-(加logo)]-->提供主机地址和端口号信息(直接使用[ThoughtWorks.QRCode.dll]比较简单 ...
- socket 异步通信的一些问题
socket通信在使用时被封装很简单,像操作文件一样简单,正是因为简单里面好多细节需要深入研究一下. windows下通信有select和iocp方式,select是传统方式,在socket里使用re ...
- Socket异步通信及心跳包同时响应逻辑分析(最后附Demo)。
有段时间没有更博了,刚好最近在做Socket通信的项目,原理大致内容:[二维码-(加logo)]-->提供主机地址和端口号信息(直接使用[ThoughtWorks.QRCode.dll]比较简单 ...
- (转)C# Socket异步通信
本文转载自:http://www.cnblogs.com/llllll/archive/2009/05/13/1455703.html 服务器端 TCPServer 1.使用的通讯通道:socket ...
- Socket 异步通信示例
这个项目是一个控制台应用程序: 服务器端: using System; using System.Net; using System.Net.Sockets; using System.Text; u ...
随机推荐
- (NO.00001)iOS游戏SpeedBoy Lite成形记(二十五)
每次压赌要打开弹出菜单还是让人略觉不爽,下面我们再添加一个随机押注的按钮:自动随机选择选手和下赌金额. 打开spriteBuilder,修改GameInterface.ccb的界面,在Run按钮旁边添 ...
- sublimeText3使用记录
sublime确实是神器,最近学习了一下,做个记录 1.下载 http://www.sublimetext.com/3 选择对应的版本安装即可(我的是win10 64位机) 2.个人配置 2.1.默认 ...
- 【Qt编程】Qt版扫雷
学习要学会举一反三.在以前的<用matlab扫扫雷>一文中,我用matlab简单的编写了一个扫雷小程序.当然,与Windows自带的扫雷程序自然是不敢相提并论.今天我就用c++来写个扫雷程 ...
- LIRe提供的图像检索算法的速度
本文翻译了LIRe的作者Mathias Lux发表的论文<LIRe: Lucene Image Retrieval - An Extensible Java CBIR Library>.主 ...
- android自定义viewgroup初步之一----抽屉菜单
转载请注明出处 http://blog.csdn.net/wingichoy/article/details/47832151 几天前在慕课网上看到鸿洋老师的 自定义卫星菜单,感觉很有意思,于是看完视 ...
- ANN实现
ANN核心数据结构: typedef struct { int input_n; /* number of input units */ int h ...
- Vim/Vi常用操作(第二版)
周围同事不是用vim就是Emacs,你要是用一ultraedit,你都不好意思跟人家打招呼;什么插件呀,语法高亮呀,拼写检查呀,能给它开的都给它开着,就是一个字儿:酷. 你说这么牛B一东西,怎么着学会 ...
- 股票K线图
代码链接地址:点击打开链接
- 【Java编程】随机数的不重复选择
随机数的不重复选择就是从n个数中随机选取m(m<n)个数.在本文中,我们用Java来实现.因此我们先介绍Java的相关知识. 在Java中,Java.util.Set接口和Java.util.L ...
- 安卓Eclipse开发者的福音
我们知道,谷歌已经放弃对Eclipse(ADT)的维护更新了,现在官网上也找不到ADT的下载链接了,我们大多数同学仍在使用的ADT版本可能已经很老了,估计大多数的SDK版本只到4.4,而,在尝试升级以 ...