这篇文章主要介绍了C# TcpClient网络编程传输文件的示例,帮助大家更好的理解和学习使用c#,感兴趣的朋友可以了解下
客户端
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("接收成功");
}
}
}
}
}
实例图
以上就是C# TcpClient网络编程传输文件的示例的详细内容,更多关于C# TcpClient传输文件的资料请关注得得之家其它相关文章!
沃梦达教程
本文标题为:C# TcpClient网络编程传输文件的示例


猜你喜欢
- 在C# 8中如何使用默认接口方法详解 2023-03-29
- Unity Shader实现模糊效果 2023-04-27
- c# 模拟线性回归的示例 2023-03-14
- C# 使用Aspose.Cells 导出Excel的步骤及问题记录 2023-05-16
- .NET CORE DI 依赖注入 2023-09-27
- user32.dll 函数说明小结 2022-12-26
- Unity3D实现渐变颜色效果 2023-01-16
- Oracle中for循环的使用方法 2023-07-04
- 如何使用C# 捕获进程输出 2023-03-10
- WPF使用DrawingContext实现绘制刻度条 2023-07-04