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;
}
}

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

Socket一些常用的方法封装的更多相关文章

  1. appium安卓自动化的 常用driver方法封装

    appium安卓自动化的 常用driver方法封装 做安卓自动化的时候,很多方法写起来会造成代码冗余,把这部分封装起来 ,添加到androidUI工具类里,随时可调用 都放在这个类下面: @Compo ...

  2. 常用js方法封装

    常用js方法封装 var myJs = { /* * 格式化日期 * @param dt 日期对象 * @returns {string} 返回值是格式化的字符串日期 */ getDates: fun ...

  3. JS常用公共方法封装

    _ooOoo_ o8888888o 88" . "88 (| -_- |) O\ = /O ____/`---'\____ .' \\| |// `. / \\||| : |||/ ...

  4. 项目常用JS方法封装--奋斗的IT青年(微信公众号)

                                                                                                        ...

  5. JavaScript常用工具方法封装

    因为工作中经常用到这些方法,所有便把这些方法进行了总结. JavaScript 1. type 类型判断 isString (o) { //是否字符串 return Object.prototype. ...

  6. 常用js方法封装使用

    // 冒泡排序 export function bubbleSort(arr) { let i = arr.length - 1; while (i > 0) { let maxIndex = ...

  7. C#常用字符串加解密方法封装

    C#中常用的字符串加密.解密方法封装,包含只加密但不解密的方法.收藏起来备用. //方法一 //须添加对System.Web的引用 //using System.Web.Security; /// & ...

  8. WebAPi添加常用扩展方法及思维发散

    前言 在WebAPi中我们通常需要得到请求信息中的查询字符串或者请求头中数据再或者是Cookie中的数据,如果需要大量获取,此时我们应该想到封装一个扩展类来添加扩展方法,从而实现简便快捷的获取. We ...

  9. JOptionPane类提示框的一些常用的方法

    JOptionPane类提示框的一些常用的方法 XMLOracleSwing 最近在做swing程序中遇到使用消息提示框的,JOptionPane类其中封装了很多的方法. 很方便的,于是就简单的整理了 ...

随机推荐

  1. cocos2d0基础知识三个音符

    1.触摸屏事件: bool HelloWorld::init() { //省略的代码的最后位 this->schedule(schedule_selector(HelloWorld::usecr ...

  2. Effective C++:条款14:在中小企业资源管理copying表现

    (一) 在一项条款说法auto_ptr和tr1::share_ptr适合heap-based资源.然而,并非所有的资源都heap-based的.换句话说不tr1::shared_ptr 和 auto_ ...

  3. TypeScript 基本语法

    TypeScript 基本语法   TypeScript 是微软开发的 JavaScript 的超集,TypeScript兼容JavaScript,可以载入JavaScript代码然后运行.TypeS ...

  4. 未能加载文件或程序集 Newtonsoft.Json, Version=4.5.0.0 的报错,解决方法

    使用httpclient测试webapi的时候客户端报错: {"未能加载文件或程序集“Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, P ...

  5. AlloyRenderingEngine

    AlloyRenderingEngine燃烧的进度条 写在前面 Github: https://github.com/AlloyTeam/AlloyGameEngine HTML 5新增了progre ...

  6. PHP+百度地图API+JAVASCRIPT实现GPS坐标与百度坐标转换的实例

    原文:PHP+百度地图API+JAVASCRIPT实现GPS坐标与百度坐标转换的实例 <!--小幅的坐标转换点位程序--> <!DOCTYPE html> <html&g ...

  7. java web.xml listener servlet 和filter加载顺序

    在该项目中总会遇到一些关于加载的优先问题.最近遇到了同样的类别似的,所以,如果你发现信息汇总下,以下是转载其他一些人,毕竟,人们写的不错.它不重复创建的轮.只是略作修改自己的观点. 首先能够肯定的是, ...

  8. SharePoint 2013 搜索SharePoint 特定列和特定文档(自己定义搜索)

    SharePoint 2013 搜索SharePoint 特定列和特定文档 1,操作步骤和图例,因语言和版本号的不同 我尽量使用抓图方式. 2.  In Central Administration, ...

  9. 前端构建利器Grunt—Bower

    runt + Bower—前端构建利器 目前比较流行的WEB开发的趋势是前后端分离.前端采用重量级的Javascript框架,比如Angular,Ember等,后端采用restful API的Web ...

  10. c语言mysql api

    原文:c语言mysql api 1.mysql_affected_rows()            //返回上次UPDATE.DELETE或INSERT查询更改/删除/插入的行数. 2.mysql_ ...