C# TcpClient網(wǎng)絡(luò)編程傳輸文件的示例
一、簡述
利用C# TcpClient在局域網(wǎng)內(nèi)傳輸文件,可是文件發(fā)送到對面的時候卻要重新命名文件的。那可不可以連著文件名與文件一起發(fā)過去呢?
二、內(nèi)容

如上圖,把文件名字符流的長度的值的字符流(這個文件名字符流長度的值固定是11位的字符串,不足11位前面補0)與文件名的字符流合為一個byte數(shù)組然后與文件發(fā)送到對面。對面接收后解析出文件名字符流長度的值后,再根據(jù)長度解析出文件名,接下來再獲取文件流。
服務(wù)端
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}文件發(fā)送成功", 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("連接失敗,找不到服務(wù)器!");
}
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("接收成功");
}
}
}
}
}
實例圖


以上就是C# TcpClient網(wǎng)絡(luò)編程傳輸文件的示例的詳細內(nèi)容,更多關(guān)于C# TcpClient傳輸文件的資料請關(guān)注腳本之家其它相關(guān)文章!
- C# 網(wǎng)絡(luò)編程之UDP
- c# 網(wǎng)絡(luò)編程之tcp
- c# 網(wǎng)絡(luò)編程之http
- 深入學(xué)習(xí)C#網(wǎng)絡(luò)編程之HTTP應(yīng)用編程(下)
- 深入學(xué)習(xí)C#網(wǎng)絡(luò)編程之HTTP應(yīng)用編程(上)
- 淺談C#網(wǎng)絡(luò)編程詳解篇
- 詳解C# 網(wǎng)絡(luò)編程系列:實現(xiàn)類似QQ的即時通信程序
- 總結(jié)C#網(wǎng)絡(luò)編程中對于Cookie的設(shè)定要點
- C# Socket網(wǎng)絡(luò)編程實例
- C#網(wǎng)絡(luò)編程基礎(chǔ)之進程和線程詳解
- c# socket網(wǎng)絡(luò)編程接收發(fā)送數(shù)據(jù)示例代碼
- C#開發(fā)之Socket網(wǎng)絡(luò)編程TCP/IP層次模型、端口及報文等探討
- C#網(wǎng)絡(luò)編程中常用特性介紹
相關(guān)文章
WinForm項目開發(fā)中WebBrowser用法實例匯總
這篇文章主要介紹了WinForm項目開發(fā)中WebBrowser用法,需要的朋友可以參考下2014-08-08
C#解決多IfElse判斷語句和Switch語句問題的方法分享
這篇文章主要為大家介紹C#如何使用設(shè)計模式中的策略模式和委托來解決多個IfElse判斷語句和Switch語句,這種替換方式在其他語言也一樣可以做到,感興趣的可以了解一下2022-12-12
C#結(jié)合JS修改解決KindEditor彈出層問題
KindEditor 是一款出色的富文本HTML在線編輯器,這里我們講述在使用中遇到的一個問題,在部署到某些 WEB 應(yīng)用項目中,點擊類似彈出層功能時,只顯示了遮罩層,而內(nèi)容層則定位無法正確顯示,所以本文給大家介紹了C#結(jié)合JS 修改解決 KindEditor 彈出層問題2024-06-06
C# 將透明圖片的非透明區(qū)域轉(zhuǎn)換成Region的實例代碼
以下代碼實現(xiàn)將一張帶透明度的png圖片的非透明部分轉(zhuǎn)換成Region輸出的方法,有需要的朋友可以參考一下2013-10-10
C#中的Linq Intersect與Except方法使用實例
這篇文章主要介紹了C#中的Linq Intersect與Except方法使用實例,本文直接給出示例代碼,需要的朋友可以參考下2015-06-06

