最近在写数据通信的时候用到的东西!希望对大家有帮助
         /// <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. Web Api 简介

    ASP.NET Web API 简介  ASP.NET MVC 4 包含了 ASP.NET Web API, 这是一个创建可以连接包括浏览器.移动设备等多种客户端的 Http 服务的新框架, ASP. ...

  2. python3.5学习笔记:linux6.4 安装python3 pip setuptools

    前言: python3应该是python的趋势所在,当然目前争议也比较大,这篇随笔的主要目的是记录在linux6.4下搭建python3环境的过程 以及碰到的问题和解决过程. 另外,如果本机安装了py ...

  3. php mysql支持emoji表情方案

    将emoji转换成utf8 然后存储到数据库,但是 效率低 public function rrr($text) { $text = 'a

  4. jQuery1.9.1源码分析--数据缓存Data模块

    jQuery1.9.1源码分析--数据缓存Data模块 阅读目录 jQuery API中Data的基本使用方法介绍 jQuery.acceptData(elem)源码分析 jQuery.data(el ...

  5. 逆序数2 HDOJ 1394 Minimum Inversion Number

    题目传送门 /* 求逆序数的四种方法 */ /* 1. O(n^2) 暴力+递推 法:如果求出第一种情况的逆序列,其他的可以通过递推来搞出来,一开始是t[1],t[2],t[3]....t[N] 它的 ...

  6. ASP.NET MVC Web API使用示例

    上篇博客讲解rest服务开发时,曾经提到过asp.net mvc中的rest api,由于篇幅原因,没有在上篇博客中进行讲解,这里专门拿出来进行讨论.还是一样引用上次的案例,用asp.net mvc提 ...

  7. Java设计模式论述

    为何须要设计模式: 模式是做事的方法,是实现目标,研磨技术的方法.这样的对高效技术不懈追求的思想,广泛见于诸多领域,比如制作精美佳肴的过程.对于不论什么一种迈向成熟的全新技艺,身处这个行业的人都须要寻 ...

  8. ubuntu 14.04 安装torch及编译环境zbstudio

    ubuntu 14.04 安装torch及编译环境zbstudio torch zbstudio 本来是安装官网给的步骤安装torch的,可是碰到一系列的问题,后来参考网上的安装方法安装成功了 官网安 ...

  9. gcc和g++头文件和库路径的寻找和添加

    对所有用户有效修改/etc/profile文件 对个人有效则修改~/.bashrc文件 #在PATH中找到可执行文件程序的路径. export PATH =$PATH:$HOME/bin (可一次指定 ...

  10. [洛谷P3158] [CQOI2011]放棋子

    洛谷题目链接:[CQOI2011]放棋子 题目描述 在一个m行n列的棋盘里放一些彩色的棋子,使得每个格子最多放一个棋子,且不同 颜色的棋子不能在同一行或者同一列.有多少祌方法?例如,n=m=3,有两个 ...