先看图:
代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.IO;
namespace tcpFileTrans
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
/// <summary>
/// 存储目录
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, EventArgs e)
{
FolderBrowserDialog fbd = new FolderBrowserDialog();
if(fbd.ShowDialog()==DialogResult.OK)
{
textBox1.Text = fbd.SelectedPath;
}
}
/// <summary>
/// 打开文件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button3_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
if(ofd.ShowDialog()==DialogResult.OK)
{
textBox3.Text=ofd.FileName;
}
}
/// <summary>
/// 启动服务器
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
TcpListener listener;
delegate void SetTextCallBack(string text);
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text.Trim() == "" || textBox3.Text.Trim() == "")
{
MessageBox.Show("请先选择目录和文件!");
}
else
{
button1.Enabled = false;
this.Text = "服务端已启动";
listener = new TcpListener(IPAddress.Any, 3000);
listener.Start();
Thread th = new Thread(new ThreadStart(ReceiveMsg));
th.Start();
th.IsBackground = true;
}
}
public void ReceiveMsg()
{
try
{
int size = 0;
int len = 0;
string path = Path.Combine(textBox1.Text, Path.GetFileName(textBox3.Text));
FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);
TcpClient client = listener.AcceptTcpClient();
NetworkStream stream = client.GetStream();
byte[] buffer = new byte[client.ReceiveBufferSize];
while ((size = stream.Read(buffer, 0, buffer.Length)) > 0)
{
fs.Write(buffer, 0, size);
len += size;
}
fs.Flush();
stream.Flush();
stream.Close();
client.Close();
}
catch { }
}
/// <summary>
/// 发送文件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button4_Click(object sender, EventArgs e)
{
if (button1.Enabled == false)
{
if (textBox1.Text.Trim() == "" || textBox3.Text.Trim() == "")
{
MessageBox.Show("目录或文件不能为空!");
}
else
{
TcpClient client = new TcpClient();
string ip = textBox2.Text;
client.Connect(IPAddress.Parse(ip), 3000);
NetworkStream ns = client.GetStream();
FileStream fs = new FileStream(textBox3.Text, FileMode.Open);
int size = 0;//初始化读取的流量为0
long len = 0;//初始化已经读取的流量
while (len < fs.Length)
{
byte[] buffer = new byte[200 * 1024];
size = fs.Read(buffer, 0, buffer.Length);
ns.Write(buffer, 0, size);
len += size;
//Pro((long)len);
}
MessageBox.Show("文件发送成功!");
fs.Flush();
ns.Flush();
fs.Close();
ns.Close();
}
}
else
{
MessageBox.Show("请先启动服务器!");
}
}
}
}
实现原理很简单:
客户端:先连接TCP,将文件用文件流的方式读入缓冲区,然后将缓冲区的数据写入网络流中存储。
服务端:接受连接请求,从网络流中读取数据,再写入指定的文件流。