最近在写数据通信的时候用到的东西!希望对大家有帮助
         /// <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 异步通信的更多相关文章

  1. socket异步通信-如何设置成非阻塞模式、非阻塞模式下判断connect成功(失败)、判断recv/recvfrom成功(失败)、判断send/sendto

    socket异步通信-如何设置成非阻塞模式.非阻塞模式下判断connect成功(失败).判断recv/recvfrom成功(失败).判断send/sendto 博客分类: Linux Socket s ...

  2. Socket异步通信学习三

    接下来是客户端部分,采用同步接收模式,在SocketClient项目中新建了一个SynServer类,用于存放socket服务器代码,和AsynServer类似,主要有4个方法: 有一个全局socke ...

  3. Socket异步通信学习二

    接下来是服务器部分,采用异步模式,新建了一个AsynServer类,用于存放socket服务器代码,主要有4个方法: 有一个全局socket,下面四个方法中都用到. Socket socket = n ...

  4. Socket异步通信学习一

    最近在做一个频谱管理项目,负责通信模块,自己也是小白,重头学起,直至今天通信基本框架已经完成,把自己在学习中的心得与大家分享一下,做一个socket系列的博文,顺便加固一下自己对socket通信的认识 ...

  5. Socket异步通信及心跳包同时响应逻辑分析。

    有段时间没有更博了,刚好最近在做Socket通信的项目,原理大致内容:[二维码-(加logo)]-->提供主机地址和端口号信息(直接使用[ThoughtWorks.QRCode.dll]比较简单 ...

  6. socket 异步通信的一些问题

    socket通信在使用时被封装很简单,像操作文件一样简单,正是因为简单里面好多细节需要深入研究一下. windows下通信有select和iocp方式,select是传统方式,在socket里使用re ...

  7. Socket异步通信及心跳包同时响应逻辑分析(最后附Demo)。

    有段时间没有更博了,刚好最近在做Socket通信的项目,原理大致内容:[二维码-(加logo)]-->提供主机地址和端口号信息(直接使用[ThoughtWorks.QRCode.dll]比较简单 ...

  8. (转)C# Socket异步通信

    本文转载自:http://www.cnblogs.com/llllll/archive/2009/05/13/1455703.html 服务器端 TCPServer 1.使用的通讯通道:socket ...

  9. Socket 异步通信示例

    这个项目是一个控制台应用程序: 服务器端: using System; using System.Net; using System.Net.Sockets; using System.Text; u ...

随机推荐

  1. 视音频编解码学习工程:TS封装格式分析器

    =====================================================视音频编解码学习工程系列文章列表: 视音频编解码学习工程:H.264分析器 视音频编解码学习工 ...

  2. 2013暑假总结-SB学习

    经过暑假的学习,使英语原本基础不好的我找到了英语学习的感觉.方向.信心,暑假的这种团队学习英语的感觉才刚刚开始,即将开学了,我们并将保持着这学习的劲头坚持努力的做下去. 暑假35天英语的全职学习,对于 ...

  3. C语言的指针的基本语法

    这是我在C++编程的一本教科书偶然看到的,就当做一个查询的资料吧

  4. Ext JS 5初探(二) ——Bootstrap.js

    在Bootstrap.js文件中,总共有1500行(包含注释和空行),使用编辑器的代码折叠功能就如下图可以一窥全貌了. 从代码可以看到,这里主要定义了Ext.Boot.Ext.globalEval.E ...

  5. mysql进阶(二十一)删除表数据

    MySQL删除表数据 在MySQL中有两种方法可以删除数据,一种是DELETE语句,另一种是TRUNCATE TABLE语句.DELETE语句可以通过WHERE对要删除的记录进行选择.而使用TRUNC ...

  6. Linux基础正则表达式字符汇整(characters)

    RE 字符 意义与范例 ^word 意义:待搜寻的字串(word)在行首! 范例:搜寻行首为 # 开始的那一行,并列出行号 grep -n '^#' regular_express.txt word$ ...

  7. thrift实现HDFS文件操作

    thrift 文件如下 namespace java com.pera.file.transform struct  File{     1:string path ,     2:string co ...

  8. 【Qt编程】基于Qt的词典开发系列<十三>音频播放

    在上一篇文章中,我是在Qt4平台上调用本地发音的,后来由于用到JSON解析,就将平台转到了Qt5,因为Qt5自带解析JSON的类.然后发现上一篇文章的方法无法运行,当然网上可以找到解决方法,我在这里直 ...

  9. 关于NSString和NSMutableString的相关用法和基本介绍

    Objective-C 中核心处理字符串的类是 NSString 与 NSMutableString ,这两个类最大的区别就是NSString 创建赋值以后该字符串的内容与长度不能在动态的更改,除非重 ...

  10. 如何使用firefox适用于javascript的debugger命令

    首先安装firebug,在firefox的扩展里搜索安装即可. 然后在页面中启用firebug中的脚本: 然后在网页某些位置加入debugger命令,比如如下页面代码: <!DOCTYPE ht ...