一个基于c#的点对点局域网文件传输小案例,运行效果截图

//界面窗体

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace 文件传输
{
public partial class Form1 : Form
{
/// <summary>
/// 文件名
/// </summary>
private string fileName;
/// <summary>
/// 文件路径
/// </summary>
private string filePath;
/// <summary>
/// 文件大小
/// </summary>
private long fileSize;
public Form1()
{
InitializeComponent();
Thread.CurrentThread.IsBackground=true;
textBox2.Text = IpUtil.GetLocalIp();
label1.Text = "您的ip:" + IpUtil.GetLocalIp() + " 您的端口:" + IpUtil.GetRandomPort();
var s= new FileRecive(this);
new Thread(s.run).Start();
}

/// <summary>
/// 信息提示框
/// </summary>
/// <param name="msg"></param>
public void Tip(string msg) {

MessageBox.Show(msg,"温馨提示");
}

/// <summary>
/// 发送文件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, EventArgs e)
{
string ip = textBox2.Text;
string port =textBox3.Text;

if (fileName.Length == 0) {

Tip("请选择文件");
return;
}
if(ip.Length==0||port.ToString().Length==0){

Tip("端口和ip地址是必须的!");
return;
}

var c = new FileSend(this,new string[]{ip,port,fileName,filePath,fileSize.ToString()});
new Thread(c.Send).Start();
}

/// <summary>
/// 选择文件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog dig = new OpenFileDialog();

dig.ShowDialog();

//获取文件名
this.fileName = dig.SafeFileName;

//获取文件路径
this.filePath = dig.FileName;

FileInfo f = new FileInfo(this.filePath);

//获取文件大小
this.fileSize = f.Length;
textBox1.Text = filePath;
}

/// <summary>
/// 更新进度条
/// </summary>
/// <param name="value"></param>
public void UpDateProgress(int value) {

this.progressBar1.Value=value;
this.label2.Text = value + "%";
System.Windows.Forms.Application.DoEvents();
}

/// <summary>
/// 修改状态
/// </summary>
/// <param name="state"></param>
public void SetState(string state) {

label5.Text = state;
}
/// <summary>
/// 退出程序
/// </summary>
public void Exit() {

Application.Exit();
}
}
}

//ip和端口工具类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace 文件传输
{
class IpUtil
{
/// <summary>
/// 获取本地ip地址
/// </summary>
/// <returns></returns>
public static string GetLocalIp()
{
string hostname = Dns.GetHostName();
IPHostEntry localhost = Dns.GetHostByName(hostname);
IPAddress localaddr = localhost.AddressList[0];
return localaddr.ToString();
}

/// <summary>
/// 产生随机端口
/// </summary>
/// <returns></returns>
public static int GetRandomPort() {

return new Random().Next(1000)+5000;
}
}
}

//文件发送类

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace 文件传输
{

//文件发送类
class FileSend
{
private TcpClient client;
private NetworkStream stream;
private string[] param;
private Form1 fm;
public FileSend(Form1 fm,params string[] param) {

this.param = param;
this.fm = fm;

}

public void Send()
{

try
{
//连接接收端
this.client = new TcpClient(param[0], int.Parse(param[1]));
string msg = param[2] + "|" + param[4];
byte[] m = Encoding.UTF8.GetBytes(msg);

while (true){
this.stream = this.client.GetStream();
this.stream.Write(m, 0, m.Length);
this.stream.Flush();
byte[] data = new byte[1024];
int len = this.stream.Read(data, 0, data.Length);
msg = Encoding.UTF8.GetString(data, 0, len);
//对方要接收我发送的文件
if (msg.Equals("1"))
{

fm.SetState("正在发送:");
FileStream os = new FileStream(param[3], FileMode.OpenOrCreate);

data = new byte[1024];
//记录当前发送进度
long currentprogress = 0;
len=0;
while ((len = os.Read(data, 0, data.Length)) > 0) {
currentprogress += len;
//更新进度条
fm.UpDateProgress((int)(currentprogress*100/long.Parse(param[4])));
this.stream.Write(data,0,len);

}
os.Flush();
this.stream.Flush();
os.Close();
this.stream.Close();
fm.Tip("发送成功!");
fm.Exit();
}
}
}
catch (Exception e)
{

fm.Tip(e.Message);

}

}
}
}

//文件接收类

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace 文件传输
{

/// <summary>
/// 文件接收类
/// </summary>
class FileRecive
{

private TcpListener server;
private Form1 fm;
private NetworkStream stream;
public FileRecive(Form1 fm) {
this.fm = fm;
try
{
this.server = new TcpListener(IPAddress.Parse(IpUtil.GetLocalIp()), IpUtil.GetRandomPort());

server.Start();
}
catch (Exception e) {

fm.Tip(e.Message);

}
}

/// <summary>
/// 接收文件
/// </summary>
public void run()
{

while (true)
{
try
{
TcpClient client = server.AcceptTcpClient();
this.stream = client.GetStream();
byte[] msgs = new byte[1024];

int len = this.stream.Read(msgs, 0, msgs.Length);

string msg = Encoding.UTF8.GetString(msgs, 0, len);

string[] tip = msg.Split('|');
if (DialogResult.Yes == MessageBox.Show(IpUtil.GetLocalIp() + "给您发了一个文件:" + tip[0] + "大小为:" + (long.Parse(tip[1]) / 1024) + "kb ,确定要接收吗?", "接收提醒", MessageBoxButtons.YesNo))
{

//将接收信息反馈给发送方
msg = "1";
msgs = Encoding.UTF8.GetBytes(msg);
this.stream.Write(msgs, 0, msgs.Length);
this.stream.Flush();
fm.SetState("正在接收:");
//开始接收文件
string path = @"C:\Users\Administrator\Desktop\" + tip[0];//接收文件的存储路径
FileStream os = new FileStream(path, FileMode.OpenOrCreate);

byte[] data = new byte[1024];
long currentprogress = 0;
int length = 0;
while ((length = this.stream.Read(data, 0, data.Length)) > 0)
{
currentprogress += length;
//更新进度条
fm.UpDateProgress((int)(currentprogress * 100 / long.Parse(tip[1])));
os.Write(data, 0, length);

}
os.Flush();
this.stream.Flush();
os.Close();
this.stream.Close();
fm.Tip("成功接收文件并存入了" + path + "中!");
fm.Exit();

}

}
catch (Exception e)
{
fm.Tip(e.Message);

}
}
}
}
}

c# 局域网文件传输实例的更多相关文章

  1. java基于P2P的聊天和文件传输实例

    用java的NIO技术编写的 1. 支持聊天功能 2. 拖拽文件能够实现文件传输功能.也能够是目录 3. 启动时能够选择server端或client端启动 4. 本人原创.学习NIO和java的网络通 ...

  2. C#实现局域网文件传输

    网络通信一般都是通过Socket进行的,称为进程通信机制,通常也称作"套接字",用于描述IP地址和端口,是一个通信链的句柄. 先学习一下socket基本原理: socket原理: ...

  3. nc 局域网聊天+文件传输(netcat)

    nc 局域网聊天+文件传输 nc的全程是netcat,这个工具非常好用. 有时候我们需要在局域网内传送一些文本消息或者文件的时候,通常的做法是安装一些局域网通讯软件,然后来做.其实不必要这样,使用nc ...

  4. python+socket实现网络信息交互及文件传输

    Socket 网络上的两个程序通过一个双向的通信连接实现数据的交换,这个连接的一端称为一个socket. Socket又称"套接字",应用程序通常通过"套接字" ...

  5. 企业网盘居然支持高速局域网文件传输工具(速度可达20M)

    高速局域网文件传输工具Mobox,局域网内文件共享是公司内非常必须的功能,原本文件共享可以通过:1)windows目录共享目录来实现文件交互:2)通过U盘拷贝给对方:3)通过QQ发送给对方:4)通过邮 ...

  6. 基于WCF的支持跨局域网可断点续传的大文件传输服务实现

    题外话:这个系列的文章记录了本人最近写的一个小工程,主要包含了两个功能,一是对文件的断点续传的功能,二是基于WCF的一对多文件主动发送的功能,顺便这也是我自己在WCF学习路上的一个小成果吧. 在网上找 ...

  7. [转]实用教程:搭建FTP服务器以实现局域网飞速传输文件

    原文地址:https://www.ithome.com/html/win10/304059.htm 相信很多人都面临过这样的问题:一个局域网下有很多设备,我们想在这些设备之间互传文件,有些文件非常大, ...

  8. 用Java开发局域网内文件传输软件遇到的一些问题

    项目地址:https://github.com/b84955189/FileTransfer 由于巨懒的我不太喜欢使用U盘操作文件,特此开发一个简易的文件传输程序. 目前仅限局域网内传输,后期会尝试写 ...

  9. Delphi 局域网点对点文件传输(IdTcpClient控件)

    unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms ...

随机推荐

  1. C#操作access和SQL server数据库代码实例

    在C#的学习中,操作数据库是比较常用的技术,而access和sql server 数据库的操作却有着不同.那么,有哪些不同呢? 首先,需要引用不同的类.因为有着不同的数据引擎. access:usin ...

  2. 使用visual studio 调试android 程序 ,真机调试

    1 使用visual studio 2015 新建 blank android APP , 2 安卓手机调整到开发者模式 3 通过USB链接到PC 4 自动检测 设备(这一步貌似没有立即检测到真机设备 ...

  3. Python全栈【Socket网络编程】

    Python全栈[socket网络编程] 本章内容: Socket 基于TCP的套接字 基于UDP的套接字 TCP粘包 SocketServer 模块(ThreadingTCPServer源码剖析) ...

  4. python address already in use

    1)找到使用端口的进程pid netstat -lp 2)kill掉pid kill -9 1234

  5. Angular2 Http

    1. 使用Http 绝大部分应用程序都会和后台服务打交道,Http是浏览器和服务器之间通讯的主要协议,通过Http调用来访问远程服务器上相应的 Web API. HttpModule 并不是 Angu ...

  6. MySql的一些用法

    1.怎样找到MySql数据的存储目录? 答:从服务中查看正在运行的MySql,查看它的启动参数,可能是这个样子: "D:\Program Files\MySQL\MySQL Server 5 ...

  7. Buffer类

    输入流中可以通过缓冲区来加大读取的效率,sun公司感觉可以加快执行效率,他就为我们提供了一个类来操作缓存区. Buffer来头的类:所有缓冲流都是以Buffer开头的: 学习缓冲流的作用: Buffe ...

  8. 多个html怎么导入相同的头部导航

    1. iframe 包含法.页头和页尾分别做成一个页面,然后通过iframe嵌入到调用的页面.这种方法在页头页尾高度固定的时候比较适用,因为当页头页尾高度不固定时,需要iframe根据页面内容自适应高 ...

  9. PHP两种基础的算法:冒泡、快速排序法》》》望能够帮助到大家

    首先扯个淡@@@@@@@@@ 算法是程序的核心,一个程序的好坏关键是这个程序算法的优劣. 冒泡排序法 原理:在要排序的一组数中,对当前还未排好的序列,从前往后对相邻的两个数依次进行比较和调整,让较大的 ...

  10. 在Mac上开启自带的Apache,httpd服务

    下面演示的是Mac自带的httpd服务 启动httpd服务 AppledeMacBook-Pro:python2_zh apple$ sudo apachectl start AppledeMacBo ...