局域网寻在线ip的socket传文件
最近公司的一个小项目中用到了socket方面的知识,于是自学了socket方面的知识。做了一个socket的寻在线ip然后传文件的例子。下面把我的做法写下来,以供自己备忘。高手免看!
构造的思路是:
socket服务端:1、通过找出局域网中的在线ip,利用ping的public void SendAsync(string hostNameOrAddress, int timeout, object userToken)函数去异步ping,如果能ping通的话返回success,否则false。这时你可以根据返回的信息动态添加这些ping通的ip地址、ip主机名等等到datagridview中。2、socket传文件,主要通过分包,首先定义包的大小a,计算文件流的总长l,再用l/a得到包的数量c,最后注意的是要判断是否有余留包(l-a*c)>0。有余留包也要传输 3、把这个要传输的文件流写到这些包里面去(byte[]),当然是要循环写入咯,有多少个包就写多少次 4、传包,socket方面的知识了(定义一个IPEndPoint、socket,socket的connect连接IPEndPoint,socket的send发送....)注意传输余留包。5、datagridview中显示传输状态
socket客户端:一个window服务,打包成安装程序。1、重写了OnStart跟OnStop。OnStart主要做socket的接受。定义IPEndPoint、Socket,利用Socket的bind绑定IPEndPoint,接着是Socket监听Listen 2、在一个while循环中一直Accept socket,一旦接受到socket传过来东西就Receive这些包(byte),写进新建的FileStream中 。注意写完要关闭FileStream跟socket 3、添加一个安装项目,把上述的window服务打包成exe
下面贴出代码:
socket服务端
遍历局域网在线ip:
for (int i = temp_qsip; i <= temp_jsip; i++)
{
Ping myPing;
myPing = new Ping();
myPing.PingCompleted += new PingCompletedEventHandler(_myPing_PingCompleted);
string pingIP = qs + i.ToString();
myPing.SendAsync(pingIP, 1000, null);
}
private void _myPing_PingCompleted(object sender, PingCompletedEventArgs e)
{//获取主机名失败后就移除它,说明是路由或者其他的设置,
try
{
if (e.Reply.Status == IPStatus.Success)
{
this.dgv.Rows.Add();
this.dgv.Rows[this.dgv.NewRowIndex - 1].Cells[0].Value = true;
this.dgv.Rows[this.dgv.NewRowIndex - 1].Cells[1].Value = Dns.GetHostByAddress(IPAddress.Parse (e.Reply.Address.ToString())).HostName;
this.dgv.Rows[this.dgv.NewRowIndex - 1].Cells[2].Value = e.Reply.Address.ToString();
this.dgv.Rows[this.dgv.NewRowIndex - 1].Cells[3].Value = "8888";
this.dgv.Rows[this.dgv.NewRowIndex - 1].Cells[4].Value = "";
}
else { }
}
catch { this.dgv.Rows.RemoveAt(this.dgv.Rows.Count-2); }
}
传输文件部分:
FileInfo cFile = new FileInfo(this.textBox1.Text);
//打开文件流
FileStream cStream = cFile.OpenRead();
//包的大小
int PacketSize = 50000;
//包的数量
int PacketCount = (int)(cStream.Length / ((long)PacketSize));
//最后一个包的大小
int LastDataPacket = (int)(cStream.Length - ((long)(PacketSize * PacketCount)));
//指向客户端节点
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(this.dgv.Rows[i].Cells[2].Value.ToString()), int.Parse(this.dgv.Rows[i].Cells[3].Value.ToString()));
//创建套接字
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//连接到发送端
client.Connect(ipep);
//发送[文件名]到客户端
serv.Module.SendVarData(client, System.Text.Encoding.Unicode.GetBytes(cFile.Name));
//数据包
byte[] data = new byte[PacketSize];
//开始循环发送数据包
for (int j = 0; j < PacketCount; j++)
{
//从文件流读取数据并填充数据包
cStream.Read(data, 0, data.Length);
//发送数据包
serv.Module.SendVarData(client, data);
}
//如果还有多余的数据包,则应该发送完毕!
if (LastDataPacket != 0)
{
data = new byte[LastDataPacket];
cStream.Read(data, 0, data.Length);
serv.Module.SendVarData(client, data);
}
//关闭套接字
client.Close();
//server.Close();
//关闭文件流
cStream.Close();
socket客户端:
protected override void OnStart(string[] args)
{
StartSocket();
}
protected override void OnStop()
{
try
{
ThreadSocket.Abort();
System.Diagnostics.Trace.Write("线程停止");
}
catch (Exception ex)
{
System.Diagnostics.Trace.Write(ex.Message);
}
}
private void StartSocket()
{
try
{
ThreadSocket = new Thread(new ThreadStart(socketRec));
ThreadSocket.Start();
System.Diagnostics.Trace.Write("线程任务开始");
}
catch (Exception ex)
{
System.Diagnostics.Trace.Write(ex.Message);
throw ex;
}
}
private void socketRec()
{
//创建一个网络端点
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, int.Parse("8888")); //固定8888端口
//创建一个套接字
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//绑定套接字到端口
server.Bind(ipep);
server.Listen(10);
while (true)
{
//确认连接
Socket client = server.Accept();
//获得[文件名]
string SendFileName = System.Text.Encoding.Unicode.GetString(Module.ReceiveVarData(client));
string dir = AppDomain.CurrentDomain.BaseDirectory;
//创建一个新文件
FileStream MyFileStream = new FileStream(dir + SendFileName, FileMode.Create, FileAccess.Write);
while (true)
{
byte[] data = Module.ReceiveVarData(client);
if (data.Length == 0)
{
break;
}
else
{
MyFileStream.Write(data, 0, data.Length);
}
}
//关闭文件流
MyFileStream.Close();
//关闭套接字
client.Close();
}
}
好了,第二篇日志,非常非常的马虎...不懂的欢迎发问!
转载请声明出处www.cnblogs.com/conger
posted on 2011-06-28 10:29 congplayer 阅读(2264) 评论(5) 编辑 收藏 举报