Socket一些常用的方法封装

时间:2022-09-15 19:57:21
  public class SocketHelper
{
/// <summary>
/// 功能描述:得到一个实例对象
/// </summary>
/// <returns>SocketHelper</returns>
public static SocketHelper GetSocketHelper()
{
try
{
return new SocketHelper();
}
catch
{
throw;
}
}
/// <summary>
/// 委托
/// </summary>
/// <param name="intport">intport</param>
/// <param name="strmsg">strmsg</param>
public delegate void RecvGBDelegate(int intport, string strmsg);
/// <summary>
/// 监听到广播事件
/// </summary>
public event RecvGBDelegate OnRecvGBMessageChanged; /// <summary>
/// 功能描述:监听广播,使用线程调用
/// 作  者:huangzh
/// 创建日期:2015-08-17 10:28:19
/// 任务编号:
/// </summary>
/// <param name="objport">监听端口</param>
public void RecvUDPGB(object objport)
{
UdpClient client = null;
try
{
if (!(objport is int))
{
throw new Exception("参数不是int类型");
}
int intport = Convert.ToInt32(objport);
client = new UdpClient(new IPEndPoint(IPAddress.Any, intport));
IPEndPoint endpoint = new IPEndPoint(IPAddress.Any, );
while (true)
{
byte[] buf = client.Receive(ref endpoint);
string strmsg = Encoding.UTF8.GetString(buf);
if (strmsg.IndexOf("CloseClient") >= )
break;
OnRecvGBMessageChanged(intport, strmsg);
}
}
catch
{
throw;
}
finally
{
if (client != null)
client.Close();
}
} /// <summary>
/// 功能描述:发送广播
/// </summary>
/// <param name="strmsg">strmsg</param>
/// <param name="intport">intport</param>
public void SendUDPGB(string strmsg, int intport)
{
try
{
SendUDPGB(Encoding.UTF8.GetBytes(strmsg), intport);
}
catch
{
throw;
}
} /// <summary>
/// 功能描述:发送广播
/// </summary>
/// <param name="buf">buf</param>
/// <param name="intport">intport</param>
public void SendUDPGB(byte[] buf, int intport)
{
UdpClient client = null;
try
{
client = new UdpClient(new IPEndPoint(IPAddress.Any, ));
IPEndPoint endpoint = new IPEndPoint(IPAddress.Parse("255.255.255.255"), intport);
client.Send(buf, buf.Length, endpoint); }
catch
{
throw;
}
finally
{
if (client != null)
{
client.Close();
}
}
} /// <summary>
/// 功能描述:接收文件
/// </summary>
/// <param name="intport">intport</param>
/// <param name="strApplicationPath">strApplicationPath</param>
/// <returns>返回值</returns>
public bool RecvFile(int intport, string strApplicationPath)
{
Socket server = null;
Socket client = null;
try
{
//创建一个网络端点
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, intport); //创建一个套接字
server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //绑定套接字到端口
server.Bind(ipep); //开始侦听(并堵塞该线程)
server.Listen(); //确认连接
client = server.Accept(); //获得客户端节点对象
IPEndPoint clientep = (IPEndPoint)client.RemoteEndPoint; //获得[文件名]
string strSendFileName = System.Text.Encoding.UTF8.GetString(TransferFiles.ReceiveVarData(client));
//获得[保存位置]
string strSavePath = System.Text.Encoding.UTF8.GetString(TransferFiles.ReceiveVarData(client));
strSendFileName = strApplicationPath + "\\" + (string.IsNullOrEmpty(strSavePath) ? "" : (strSavePath + "\\")) + strSendFileName;
string strdir = Path.GetDirectoryName(strSendFileName);
if (!Directory.Exists(strdir))
{
Directory.CreateDirectory(strdir);
}
//获得[包的大小]
string strbagSize = System.Text.Encoding.UTF8.GetString(TransferFiles.ReceiveVarData(client));
//MessageBox.Show("包大小" + bagSize); //获得[包的总数量]
int intbagCount = int.Parse(System.Text.Encoding.UTF8.GetString(TransferFiles.ReceiveVarData(client)));
//MessageBox.Show("包的总数量" + bagCount); //获得[最后一个包的大小]
string strbagLast = System.Text.Encoding.UTF8.GetString(TransferFiles.ReceiveVarData(client));
//MessageBox.Show("最后一个包的大小" + bagLast); //创建一个新文件
using (FileStream myFileStream = new FileStream(strSendFileName, FileMode.Create, FileAccess.Write))
{
//已发送包的个数
int intSendedCount = ; while (true)
{
byte[] data = TransferFiles.ReceiveVarData(client);
if (data.Length == )
{
break;
}
else
{
intSendedCount++;
//将接收到的数据包写入到文件流对象
myFileStream.Write(data, , data.Length);
//显示已发送包的个数
//MessageBox.Show("已发送包个数"+SendedCount.ToString());
}
}
}
}
catch
{
throw;
}
finally
{
//关闭套接字
if (client != null)
client.Close();
if (server != null)
server.Close(); }
return true;
} /// <summary>
/// 功能描述:发送文件
/// </summary>
/// <param name="strfile">文件路径</param>
/// <param name="strDirName">发布相对位置</param>
/// <param name="toip">目标ip</param>
/// <param name="inttoPort">目标端口</param>
public void SendFile(
string strfile,
string strDirName,
IPAddress toip,
int inttoPort)
{
Socket client = null;
try
{
//创建一个文件对象
FileInfo ezoneFile = new FileInfo(strfile);
//打开文件流
using (FileStream ezoneStream = ezoneFile.OpenRead())
{
//包的大小
int intPacketSize = ;
//包的数量
int intPacketCount = (int)(ezoneStream.Length / ((long)intPacketSize));
//this.textBox8.Text=PacketCount.ToString();
//this.progressBar1.Maximum=PacketCount;
//最后一个包的大小
int intLastDataPacket = (int)(ezoneStream.Length - ((long)(intPacketSize * intPacketCount))); //指向远程服务端节点
IPEndPoint ipep = new IPEndPoint(toip, inttoPort);
//创建套接字
client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//连接到发送端
client.Connect(ipep); //获得客户端节点对象
IPEndPoint clientep = (IPEndPoint)client.RemoteEndPoint;
//获得客户端的IP地址
//this.textBox7.Text=clientep.Address.ToString();
//发送[文件名]到客户端
TransferFiles.SendVarData(client, System.Text.Encoding.UTF8.GetBytes(ezoneFile.Name));
//发送[保存位置]到客户端
strDirName = strDirName.Trim(new char[] { '\\' });
TransferFiles.SendVarData(client, System.Text.Encoding.UTF8.GetBytes(strDirName));
//发送[包的大小]到客户端
TransferFiles.SendVarData(client, System.Text.Encoding.UTF8.GetBytes(intPacketSize.ToString()));
//发送[包的总数量]到客户端
TransferFiles.SendVarData(client, System.Text.Encoding.UTF8.GetBytes(intPacketCount.ToString()));
//发送[最后一个包的大小]到客户端
TransferFiles.SendVarData(client, System.Text.Encoding.UTF8.GetBytes(intLastDataPacket.ToString())); //数据包
byte[] data = new byte[intPacketSize];
//开始循环发送数据包
for (int i = ; i < intPacketCount; i++)
{
//从文件流读取数据并填充数据包
ezoneStream.Read(data, , data.Length);
//发送数据包
TransferFiles.SendVarData(client, data);
////显示发送数据包的个数
//this.textBox10.Text=((int)(i+1)).ToString();
////进度条值的显示
//this.progressBar1.PerformStep();
} //如果还有多余的数据包,则应该发送完毕!
if (intLastDataPacket != )
{
data = new byte[intLastDataPacket];
ezoneStream.Read(data, , data.Length);
TransferFiles.SendVarData(client, data);
// this.progressBar1.Value=this.progressBar1.Maximum;
}
}
}
catch
{
throw;
}
finally
{
if (client != null)
client.Close();
}
} /// <summary>
/// 功能描述:发送信息
/// </summary>
/// <param name="ip">ip</param>
/// <param name="intport">intport</param>
/// <param name="strmsg">msg</param>
public void SendMsg(
IPAddress ip,
int intport,
string strmsg)
{
UdpClient uc = null;
try
{
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(strmsg);
uc = new UdpClient();
uc.Send(bytes, bytes.Length, ip.ToString(), intport); }
catch
{
throw;
}
finally
{
if (uc != null)
{
uc.Close();
}
}
}
/// <summary>
/// 监听委托
/// </summary>
/// <param name="strmsg">strmsg</param>
public delegate void RecvMsgDelegate(string strmsg);
/// <summary>
/// 监听事件
/// </summary>
public event RecvMsgDelegate OnRecvMsg; /// <summary>
/// 功能描述:接收信息
/// </summary>
/// <param name="objport">objport</param>
public void RecvMsg(object objport)
{
if (!(objport is int))
{
throw new Exception("参数不是int类型");
}
int intport = Convert.ToInt32(objport);
UdpClient uc = null;
try
{
uc = new UdpClient(intport);
IPEndPoint iep = new IPEndPoint(IPAddress.Any, );
while (true)
{
string strtext = System.Text.Encoding.UTF8.GetString(uc.Receive(ref iep));
if (strtext == "Close")
break;
OnRecvMsg(strtext);
}
uc.Close();
}
catch
{
throw;
}
finally
{
if (uc != null)
{
uc.Close();
}
}
} public IPAddress GetThisIPAddress()
{
try
{
string strhostName = Dns.GetHostName();
IPAddress[] addressList = Dns.GetHostAddresses(strhostName);
IPAddress thisIp = null;
foreach (IPAddress item in addressList)
{
if (item.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
thisIp = item;
break;
}
}
return thisIp;
}
catch
{
throw;
}
}
}
  public class TransferFiles
{
/// <summary>
/// 功能描述:发送数据
/// </summary>
/// <param name="s">s</param>
/// <param name="data">data</param>
/// <returns>返回值</returns>
public static int SendData(Socket s, byte[] data)
{
int inttotal = ;
int intsize = data.Length;
int intdataleft = intsize;
int intsent; while (inttotal < intsize)
{
intsent = s.Send(data, inttotal, intdataleft, SocketFlags.None);
inttotal += intsent;
intdataleft -= intsent;
} return inttotal;
} /// <summary>
/// 功能描述:接收数据
/// </summary>
/// <param name="s">s</param>
/// <param name="intsize">size</param>
/// <returns>返回值</returns>
public static byte[] ReceiveData(Socket s, int intsize)
{
int inttotal = ;
int intdataleft = intsize;
byte[] data = new byte[intsize];
int intrecv;
while (inttotal < intsize)
{
intrecv = s.Receive(data, inttotal, intdataleft, SocketFlags.None);
if (intrecv == )
{
data = null;
break;
} inttotal += intrecv;
intdataleft -= intrecv;
}
return data;
} /// <summary>
/// 功能描述:发送数据
/// </summary>
/// <param name="s">s</param>
/// <param name="data">data</param>
/// <returns>返回值</returns>
public static int SendVarData(Socket s, byte[] data)
{
int inttotal = ;
int intsize = data.Length;
int intdataleft = intsize;
int intsent;
byte[] datasize = new byte[];
datasize = BitConverter.GetBytes(intsize);
intsent = s.Send(datasize); while (inttotal < intsize)
{
intsent = s.Send(data, inttotal, intdataleft, SocketFlags.None);
inttotal += intsent;
intdataleft -= intsent;
} return inttotal;
} /// <summary>
/// 功能描述:接收数据
/// </summary>
/// <param name="s">s</param>
/// <returns>返回值</returns>
public static byte[] ReceiveVarData(Socket s)
{
int inttotal = ;
int intrecv;
byte[] datasize = new byte[];
intrecv = s.Receive(datasize, , , SocketFlags.None);
int intsize = BitConverter.ToInt32(datasize, );
int intdataleft = intsize;
byte[] data = new byte[intsize];
while (inttotal < intsize)
{
intrecv = s.Receive(data, inttotal, intdataleft, SocketFlags.None);
if (intrecv == )
{
data = null;
break;
}
inttotal += intrecv;
intdataleft -= intrecv;
}
return data;
}
}

包含了:广播,消息,发送文件等