TcpListener和TcpClient传输文件

C#里面的socket编程,以下是我写的一个简单里面,是用户客户端接收服务端文件用的。

参考了msdn官网里面的例子(tcp聊天例子);本人菜鸟,写的不好请见谅。

https://docs.microsoft.com/zh-cn/dotnet/api/system.net.sockets.tcplistener?view=net-5.0

https://docs.microsoft.com/zh-cn/dotnet/api/system.net.sockets.tcpclient?view=net-5.0

首先百度一些socket的概念,如下(具体我不太懂)

Socket【套接字】
用于两个程序之间通信,描述IP地址和port端口号。
根据通信质量和效率要求,分为几种协议传输数据。

(1)TCP协议
TCP是一种面向连接的、可靠的,基于字节流的传输层通信协议。这种协议确保了数据传输的可靠性,但是效率比较低。

(2)UDP协议
UDP是一种简单的、面向数据报的无连接的协议。这种协议虽然不能提供可靠的数据传输,但是效率很高。
 

下面开始写tcp传输文件的例子代码:

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

namespace SocketTest2
{

    /// <summary>
    /// 服务器端
    /// </summary>
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Server Listening");
            TcpListener listener = null;

            try
            {
                listener = new TcpListener(IPAddress.Parse("127.0.0.1"), 50012);
                listener.Start();

                while (true)
                {
                    TcpClient client = listener.AcceptTcpClient();

                    if (client.Connected)
                    {
                        Console.WriteLine("client connected");
                        FileStream fstream = new FileStream("D:\\SocketTest2\\bin\\testmo.txt", FileMode.Open, FileAccess.Read);

                        NetworkStream networksm = client.GetStream();

                        int readSize = 0;
                        long fileLength = 0;

                        while (fileLength < fstream.Length)
                        {
                            byte[] bff = new byte[1024];
                            readSize= fstream.Read(bff, 0, bff.Length);
                            networksm.Write(bff, 0, readSize);

                            fileLength += readSize;
                        }//end while send file

                        //close client and stream
                        fstream.Flush();
                        networksm.Flush();
                        fstream.Close();
                        networksm.Close();
                        client.Close();
                        Console.WriteLine("file has already send to client");
                    }

                }//end while listen 
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                if (listener != null) {
                    listener.Stop();
                }
            }

            Console.ReadKey();
            Console.WriteLine("Process END");
        }
    }







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

namespace SocketClient2
{
    /// <summary>
    /// 客户端
    /// </summary>
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("TCP Client begin to receive");
            TcpClient client = null;
            try
            {
                client = new TcpClient("127.0.0.1", 50012);

                if (client.Connected)
                {
                    NetworkStream networksm = client.GetStream();

                    string dirPath =AppDomain.CurrentDomain.BaseDirectory + "\\WebFile";
                    if (Directory.Exists(dirPath) == false) {
                        Directory.CreateDirectory(dirPath);
                    }
                    dirPath += "\\testmo.txt";
                    FileStream fstream = new FileStream(dirPath, FileMode.Create, FileAccess.Write);

                    int readSize = 0;
                    byte[] bff = new byte[1024];

                    while (  ( readSize= networksm.Read(bff , 0 , bff.Length)) > 0)
                    {
                        fstream.Write(bff, 0, readSize);
                    }//end while write network new file

                    //close tcp connection
                    fstream.Flush();
                    fstream.Close();
                    networksm.Flush();
                    networksm.Close();
                    Console.WriteLine("receive file success");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                if (client != null)
                {
                    client.Close();
                }
            }

            Console.ReadKey();
            Console.WriteLine("client end process");
        }

    }







}

备注:

(1)代码里面的ip地址  127.0.0.1 代表本机(localhost);大家可以在内网中测试不同的IP地址。内网中的IP地址要可以互相ping通才行。

(2)发送或者接收文件数据的时候,定义了一个固定长度的byte[ ]  数组,由于不同文件的大小是不同的,有的几KB,有的几MB , 所以要用while语句循环将stream 处理。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
VB.NET是一种面向对象的编程语言,在网络通信领域中,可以使用VB.NET来进行TCP文件传输。TCP是传输控制协议(Transmission Control Protocol)的缩写,它是一种可靠的、面向连接的协议。下面我将简要介绍如何使用VB.NET进行TCP文件传输。 首先,我们需要建立一个TCP服务器和一个TCP客户端。服务器负责接收文件,客户端负责发送文件。在VB.NET中,可以使用TcpListener类来创建服务器端,使用TcpClient类来创建客户端。 在服务器端,我们首先需要绑定IP地址和端口号,使用TcpListener的构造函数即可完成。然后,调用Start方法开始监听客户端的连接请求。当客户端连接成功后,我们可以通过AcceptTcpClient方法获取到客户端的TcpClient对象。 在客户端,我们需要连接服务器,同样使用TcpClient的构造函数即可。然后,调用Connect方法连接服务器。连接成功后,我们可以通过TcpClient对象的GetStream方法获取到网络流。 接下来,我们可以使用NetworkStream类来实现文件传输。在服务器端,可以使用NetworkStream的Read方法从客户端接收数据,使用FileStream类来写入到文件中。在客户端,可以使用NetworkStream的Write方法将文件数据发送给服务器端。 最后,不要忘记关闭连接和释放资源。在服务器端,可以使用TcpListener的Stop方法停止监听,关闭TcpClient的连接;在客户端,可以关闭TcpClient的连接。 总的来说,使用VB.NET进行TCP文件传输需要注意细节和异常处理,例如处理文件接收的大小、处理连接的异常等。但是通过以上步骤,我们可以实现简单的TCP文件传输。这只是一个简单的介绍,实际操作中还有很多需要考虑的因素,例如文件的压缩、断点续传等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值