C# TcpClient网络编程传输文件的示例
作者:空白凌乱感 发布时间:2021-10-16 16:01:13
标签:C#,TcpClient,传输文件,网络编程
目录
一、简述
二、内容
一、简述
利用C# TcpClient在局域网内传输文件,可是文件发送到对面的时候却要重新命名文件的。那可不可以连着文件名与文件一起发过去呢?
二、内容
如上图,把文件名字符流的长度的值的字符流(这个文件名字符流长度的值固定是11位的字符串,不足11位前面补0)与文件名的字符流合为一个byte数组然后与文件发送到对面。对面接收后解析出文件名字符流长度的值后,再根据长度解析出文件名,接下来再获取文件流。
服务端
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace TCPSendFile
{
public partial class Form1 : Form
{
public delegate void TxtReceiveAddContentEventHandler(string txtValue);
public Form1()
{
InitializeComponent();
}
public void TxtAddContent(string txtValue)
{
if (textBox1.InvokeRequired)
{
TxtReceiveAddContentEventHandler addContent = TxtAddContent;
textBox1.Invoke(addContent, new object[] { txtValue });
}
else
{
textBox1.Text = txtValue + "\r\n" + textBox1.Text;
}
}
private void button1_Click(object sender, EventArgs e)
{
TcpListener tcpListener = new TcpListener(IPAddress.Any, 18001);
tcpListener.Start();
textBox1.Text = "开始侦听...";
Thread thread = new Thread(SendFileFunc);
thread.Start(tcpListener);
thread.IsBackground = true;
}
public void SendFileFunc(object obj)
{
TcpListener tcpListener = obj as TcpListener;
while (true)
{
try
{
TcpClient tcpClient = tcpListener.AcceptTcpClient();
if (tcpClient.Connected)
{
NetworkStream stream = tcpClient.GetStream();
string fileName = "testfile.rar";
byte[] fileNameByte = Encoding.Unicode.GetBytes(fileName);
byte[] fileNameLengthForValueByte = Encoding.Unicode.GetBytes(fileNameByte.Length.ToString("D11"));
byte[] fileAttributeByte = new byte[fileNameByte.Length + fileNameLengthForValueByte.Length];
fileNameLengthForValueByte.CopyTo(fileAttributeByte, 0); //文件名字符流的长度的字符流排在前面。
fileNameByte.CopyTo(fileAttributeByte, fileNameLengthForValueByte.Length); //紧接着文件名的字符流
stream.Write(fileAttributeByte, 0, fileAttributeByte.Length);
FileStream fileStrem = new FileStream(Application.StartupPath + "\\WebFile\\" + fileName, FileMode.Open);
int fileReadSize = 0;
long fileLength = 0;
while (fileLength < fileStrem.Length)
{
byte[] buffer = new byte[2048];
fileReadSize = fileStrem.Read(buffer, 0, buffer.Length);
stream.Write(buffer, 0, fileReadSize);
fileLength += fileReadSize;
}
fileStrem.Flush();
stream.Flush();
fileStrem.Close();
stream.Close();
TxtAddContent(string.Format("{0}文件发送成功", fileName));
}
}
catch (Exception ex)
{
}
}
}
}
}
客户端
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace TCPReceiveFile
{
public partial class Form1 : Form
{
public delegate void TxtReceiveAddContentEventHandler(string txtValue);
public Form1()
{
InitializeComponent();
}
public void TxtReceiveAddContent(string txtValue)
{
if (txtReceive.InvokeRequired)
{
TxtReceiveAddContentEventHandler addContent = TxtReceiveAddContent;
txtReceive.Invoke(addContent, new object[] { txtValue });
}
else
{
txtReceive.Text = txtValue + "\r\n" + txtReceive.Text;
}
}
private void button1_Click(object sender, EventArgs e)
{
IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse("192.168.1.101"), 18001);
TxtReceiveAddContent("连接中。。。。。");
Thread th = new Thread(ReceiveFileFunc);
th.Start(ipEndPoint);
th.IsBackground = true;
}
private void ReceiveFileFunc(object obj)
{
IPEndPoint ipEndPoint = obj as IPEndPoint;
TcpClient tcpClient = new TcpClient();
try
{
tcpClient.Connect(ipEndPoint);
}
catch
{
TxtReceiveAddContent("连接失败,找不到服务器!");
}
if (tcpClient.Connected)
{
NetworkStream stream = tcpClient.GetStream();
if (stream != null)
{
byte[] fileNameLengthForValueByte = Encoding.Unicode.GetBytes((256).ToString("D11"));
byte[] fileNameLengByte = new byte[1024];
int fileNameLengthSize = stream.Read(fileNameLengByte, 0, fileNameLengthForValueByte.Length);
string fileNameLength = Encoding.Unicode.GetString(fileNameLengByte, 0, fileNameLengthSize);
TxtReceiveAddContent("文件名字符流的长度为:" + fileNameLength);
int fileNameLengthNum = Convert.ToInt32(fileNameLength);
byte[] fileNameByte = new byte[fileNameLengthNum];
int fileNameSize = stream.Read(fileNameByte, 0, fileNameLengthNum);
string fileName = Encoding.Unicode.GetString(fileNameByte, 0, fileNameSize);
TxtReceiveAddContent("文件名为:" + fileName);
string dirPath = Application.StartupPath + "\\WebFile";
if(!Directory.Exists(dirPath))
{
Directory.CreateDirectory(dirPath);
}
FileStream fileStream = new FileStream(dirPath + "\\" + fileName, FileMode.Create, FileAccess.Write);
int fileReadSize = 0;
byte[] buffer = new byte[2048];
while ((fileReadSize = stream.Read(buffer, 0, buffer.Length)) > 0)
{
fileStream.Write(buffer, 0, fileReadSize);
}
fileStream.Flush();
fileStream.Close();
stream.Flush();
stream.Close();
tcpClient.Close();
TxtReceiveAddContent("接收成功");
}
}
}
}
}
实例图
来源:https://www.cnblogs.com/kongbailingluangan/p/6476855.html


猜你喜欢
- Task的MSDN的描述如下:【Task类的表示单个操作不会返回一个值,通常以异步方式执行。Task对象是一种的中心思想基于任务的异步模式首
- 说实话,关于Android中对短信的一些相关操作是一个比较入门的东西。那我现在还要来写这一篇博客的原因只是因为现在开发中有相关内容,而又想将
- spring security中遇到的问题1.An Authentication object was not found in the S
- 对于开发游戏项目的同胞来说,Timer 这个东西肯定不会陌生,今天对以前自己经常使用的定时进行了一番小小的总结!没有写具体实现的原理,只是列
- 一、Druid简介Druid是阿里开源的数据库连接池,作为后起之秀,性能比dbcp、c3p0更高,使用也越来越广泛。当然Druid不仅仅是一
- 项目结构项目路径可以自己定义,只要路径映射正确就可以pom.xml <properties> <spring.versio
- 前言1.因为涉及到对象锁,Wait、Notify一定要在synchronized里面进行使用。2.Wait必须暂定当前正在执行的线程,并释放
- //字符串的内存驻留机制 public static v
- Unsafe类介绍第一次看到这个类时被它的名字吓到了,居然还有一个类自名Unsafe?读完本文,大家也能发现Unsafe类确实有点不那么安全
- 问题在本地启动dubbo时,服务注册在本地的zookeeper ,但是注册IP却不是本地的iP。产生问题,导致consumer 找不到pro
- Android中的ListView应该算是布局中几种最常用的组件之一了,使用也十分方便,下面将介绍ListView几种比较常见的优化方法:首
- 概述异步这个概念在不同语境下有不同的解释,比如在一个单核CPU里开启两个线程执行两个函数,通常认为这种调用是异步的,但对于CPU来说它是单核
- 首先我们建立两个数据库(可以不在同一台电脑上):multiple_order:DROP DATABASE IF EXISTS `multip
- springboot URL带有斜杠的转义字符百分之2F导致的400错误今天项目上出现一个问题,是前端的GET请求url中带有路径参数,这个
- 本地仓库主要是一种缓存,当你使用远程仓库中下载组件后,它下一次会优先从本地进行加载,一般位于USER_HOME/.m2目录下,我们自己也可以
- 1-:生成一个签名密钥你可以用keytool命令生成一个私有密钥。在Windows上keytool命令放在JDK的bin目录中(比如C:\P
- 1.使用API设置主题如下所示,在Activity中使用setThemesetTheme(R.style.MyTheme1);2.调用API
- 最近过年发红包拜年成为一种新的潮流,作为程序猿对算法的好奇远远要大于对红包的好奇,这里介绍一种自己想到的一种随机红包分配策略,还请大家多多指
- 本文实例讲述了Android编程实现简单文件浏览器功能。分享给大家供大家参考,具体如下:运行效果:布局:<LinearLayout x
- 在许多APP中,有的搜索框是一直固定的,有的呢,附加了很多的效果,就比如京东好吧,谁让京东那么厉害呢,不说了,开始 * !原理:就是自定义sc