📄 cngpsocket.cs
字号:
using System;
using System.Net;
using System.Net.Sockets;
using Pierce.MyIPAddress;
using WriteLog;
using Pierce.AttributeClass;
namespace Cngp
{
/// <summary>
/// CngpSocket:
/// 2004-11-05: 增加Socket状态检查,如果Socket断开,那么重新连接
/// </summary>
[LastModified("2006-03-14","使用简答任务,每个函数只作自己的工作,不做其它,便于查错")]
public class CngpSocket
{
private Socket socket;
private Logs logit=new Logs();
private MyIPAddress ipAddress=new MyIPAddress();
private string IpAddress;
private int Port;
/// <summary>
/// 构造函数
/// </summary>
public CngpSocket()
{
}
/// <summary>
/// 属性,读写,工作Socket
/// </summary>
public Socket WorkSocket
{
get{return socket;}
set{socket=value;}
}
/// <summary>
/// 初始化连接
/// </summary>
/// <param name="IpAddress">网关IP地址</param>
/// <param name="Port">网关端口</param>
/// <returns>返回连接bool值</returns>
public bool Init(string IpAddress,int Port)
{
this.IpAddress=IpAddress;
this.Port=Port;
if(SocketConnect())
{
return true;
}
else
{
return false;
}
}
/*-----------------------------------------------
* 2006-03-14:注销
*
/// <summary>
/// 检查Socket状态,如果异常,那么重新连接
/// </summary>
private void SocketCheck()
{
try
{
if(socket==null)
{
SocketConnect();
}
else
{
if(socket.Connected )
{
if(!socket.Poll(-1,SelectMode.SelectWrite))
{
socket.Shutdown(SocketShutdown.Both);
socket.Close();
//重新连接
SocketConnect();
}
}
else
{
socket.Shutdown(SocketShutdown.Both);
socket.Close();
//重新连接
SocketConnect();
}
}
}
catch(SocketException ex)
{
Logs.writeLog(String.Concat(
ex.ErrorCode.ToString(),
"\r\n",
ex.NativeErrorCode.ToString(),
"\r\n",
ex.Message,
"\r\n",
ex.StackTrace,
"\r\n",
ex.TargetSite.ToString(),
"\r\n",
ex.Source),false);
}
}
----------------------------*/
/// <summary>
/// 同目的主机连接
/// </summary>
/// <returns>返回是否连接的Bool值</returns>
private bool SocketConnect()
{
try
{
IPEndPoint endPoint=new IPEndPoint(IPAddress.Parse(IpAddress),Port);
socket=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
//
//设置Socket的参数
//
socket.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.SendTimeout,ConfigInformation.SendTimeout);
socket.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.ReceiveTimeout,ConfigInformation.ReceiveTimeout);
LingerOption lingeroption=new LingerOption(true,ConfigInformation.Lingertime);
socket.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.Linger,lingeroption);
//
//socket连接网关
//
socket.Connect(endPoint);
//返回
return true;
}
catch
{
return false;
}
}
/// <summary>
/// 发送信息
/// </summary>
/// <param name="Message">发送信息内容</param>
/// <param name="Size"发送信息长度</param>
/// <returns>返回发送字节数</returns>
[LastModified("2006-03-14","发送前停止检查Socket状态,发送只作发送工作,使用简单任务")]
private int SendToIsmg(byte[] Message,int Size)
{
//Send
int SendBytes=SendData(socket,Message);
return SendBytes;
}
/// <summary>
/// 发送信息,重载
/// </summary>
/// <param name="Message"></param>
/// <returns></returns>
public int SendToIsmg(byte[] Message)
{
//
//检查Socket状态,是否可写,否则抛出异常
//
if(!socket.Poll(-1,SelectMode.SelectWrite))
{
throw new Exception("Socket Can't be Written");
}
return SendToIsmg(Message,(int)Message.Length);
}
/// <summary>
/// 从网关接收信息
/// </summary>
/// <param name="PartMessage">返回的内容数组,不包括前4位长度</param>
/// <returns></returns>
[LastModified("2006-03-13","停止使用SocketCheck函数,因为是读操作,不是写操作")]
public uint ReceiveFromIsmg(ref byte[] PartMessage,ref uint Length)
{
//
//检查Socket状态,是否可读,否则抛出异常
//
if(!socket.Poll(-1,SelectMode.SelectRead))
{
throw new Exception("Socket Can't be Read");
}
//
byte[] ByteLength=new byte[4];//接收长度字节数组
//接收前4位,即长度
ByteLength=ReceiveData(socket,4);
//转换字节顺序,获取长度
Length=ipAddress.NetworkToHostOrder(BitConverter.ToUInt32(ByteLength,0));
//
PartMessage=new byte[Length-4];
//接收剩余的数据
PartMessage=ReceiveData(socket,(int)(Length-4));
return 1;
}
/// <summary>
/// 关闭socket
/// </summary>
public void Exit()
{
try
{
if(socket.Connected)
{
socket.Shutdown(SocketShutdown.Both);
socket.Close();
}
}
catch
{
socket=null;
}
}
/// <summary>
/// 发送数据的方法
/// </summary>
/// <param name="socket">Socket 连接</param>
/// <param name="data">要发送的字节数组</param>
/// <returns>返回发送的字节数</returns>
public int SendData(Socket socket,byte[] data)
{
int total=0; //已经发送的字节数
int size=data.Length; //总的字节数
int dataleft=size; //剩余的字节数
int sent=0;
//循环发送数据
while(total<size)
{
sent=socket.Send(data,total,dataleft,SocketFlags.None);
total+=sent;
dataleft-=sent;
}
return total;
}
/// <summary>
/// 接收数据的方法
/// </summary>
/// <param name="socket">Socket连接</param>
/// <param name="size">要接收的数据长度</param>
/// <returns>返回收到的字节数组</returns>
public byte[] ReceiveData(Socket socket,int size)
{
int total=0; //收到的总的字节数
int dataleft=size; //剩余的字节数
byte[] data=new byte[size]; //接收数据的数组
int rece=0; //收到的字节数
//循环接收数据
while(total<size)
{
rece=socket.Receive(data,total,dataleft,SocketFlags.None);
//如果收到的字节数为0,那么说明连接断开,返回空的字节数组
if(rece==0)
{
break;
}
total+=rece; //收到的字节数长度++
dataleft-=rece; //剩余的字节数--
}
return data; //返回
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -