首页 > 编程语言 >C# Socket 文件发送传输

C# Socket 文件发送传输

时间:2024-04-26 09:23:10浏览次数:28  
标签:Console Socket C# System 传输 WriteLine new using string

客户端向服务器发送文件:

服务器:

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

namespace Server
{
class Program
{
static void Main(string[] args)
{
IPEndPoint ip = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8080);
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sock.Bind(ip);
sock.Listen(1);

        while(true)
        {
            Socket client = sock.Accept();

            if (client.Connected)
            {
                Thread clientThread = new Thread(new ParameterizedThreadStart(MyClient));
                clientThread.IsBackground = true;
                clientThread.Start(client);
            }
        }
    }

    private const int BUFFERSIZE = 1024/* * 1024*/;
    private static string _path = @"D:\";

    private static void MyClient(object socket)
    {
        Socket clientSocket = socket as Socket;
        string clientName = clientSocket.RemoteEndPoint.ToString();
        Console.WriteLine("新客户端连接:" + clientName);

        try
        {
            while(true)
            {
                byte[] buffer = new byte[BUFFERSIZE];
                int countReceive = clientSocket.Receive(buffer);
                string receiveStr = Encoding.Default.GetString(buffer, 0, countReceive);
                Console.WriteLine("收到:" + clientName + ":" + receiveStr);
                string[] command = receiveStr.Split(',');

                string fileName = null;
                long fileLength = -1L;

                if (command[0] == "nameAndLength")
                {
                    fileName = command[1];
                    fileLength = long.Parse(command[2]);
                    clientSocket.Send(Encoding.Default.GetBytes("ok"));
                    Console.WriteLine("接收文件:" + fileName + " 请等候……");

                    long recieved = 0L;

                    using (FileStream fsWriter = new FileStream(Path.Combine(_path,fileName), FileMode.Create, FileAccess.Write, FileShare.None))
                    {
                        int recive;

                        while(recieved < fileLength)
                        {
                            recive = clientSocket.Receive(buffer);
                            fsWriter.Write(buffer, 0, recive);
                            fsWriter.Flush();
                            recieved += recive;
                            Console.WriteLine("已接收数据:{0}/{1}", recieved.ToString(), fileLength.ToString());
                        }

                        Console.WriteLine("接收完成……\n");
                    }
                }
            }
        }
        catch (Exception)
        {
            Console.WriteLine("客户端:" + clientName + "退出");
        }
    }
}

}
客户端:

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

namespace Client
{
class Program
{
private static Socket _sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

    static void Main(string[] args)
    {
        _sock.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8080));
        Console.WriteLine("连接成功…");

        while (true)
        {
            Console.WriteLine("请输入需要发送的文件路径:");
            string path = Console.ReadLine();

            try
            {
                using (FileStream fsReader = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.None))
                {
                    long sended = 0L;
                    long fileLength = fsReader.Length;
                    string fileName = Path.GetFileName(path);
                    string sendStr = "nameAndLength," + fileName + "," + fileLength.ToString();

                    _sock.Send(Encoding.Default.GetBytes(sendStr));

                    const int BUFFERSIZE = 1024/* * 1024*/;
                    byte[] buffer = new byte[32];

                    int recvCount = _sock.Receive(buffer);
                    string mes = Encoding.Default.GetString(buffer, 0, recvCount);

                    if (mes == "ok")
                    {
                        Console.WriteLine("发送文件:" + fileName + " 请等待……");
                        byte[] fileBuffer = new byte[BUFFERSIZE];

                        int readCount;
                        int sending;
                        int readCountLeft;

                        while ((readCount = fsReader.Read(fileBuffer, 0, BUFFERSIZE)) != 0)
                        {
                            sending = 0;
                            readCountLeft = readCount;
                            while ((sending += _sock.Send(fileBuffer, sending, readCountLeft, SocketFlags.None)) < readCount) // 判断发送完
                            {
                                readCountLeft = readCount - sending;
                            }
                            sended += sending;
                            Console.WriteLine("发送数据:{0}/{1}", sended.ToString(), fileLength.ToString());
                        }

                        Console.WriteLine("发送完毕……\n");
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}

}

命令行
客户端向服务器发文件。

服务器:

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

namespace Server
{
class Program
{
/exe 127.0.0.1 8080 D:\/
static void Main(string[] args)
{
int port = int.Parse(args[1]);
_path = args[2];
Console.WriteLine("开启服务器:{0}", args[0] + " " + args[1]);
IPEndPoint ip = new IPEndPoint(IPAddress.Parse(args[0]), port);
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sock.Bind(ip);
sock.Listen(100);

        while (true)
        {
            Socket client = sock.Accept();

            if (client.Connected)
            {
                Thread clientThread = new Thread(new ParameterizedThreadStart(MyClient));
                clientThread.IsBackground = true;
                clientThread.Start(client);
            }
        }
    }

    private const int BUFFERSIZE = 1024 * 1024;
    private static string _path = @"D:\";

    private static void MyClient(object socket)
    {
        Socket clientSocket = socket as Socket;
        string clientName = clientSocket.RemoteEndPoint.ToString();
        Console.WriteLine("新客户端连接:" + clientName);

        try
        {
            while (true)
            {
                byte[] buffer = new byte[BUFFERSIZE];
                int countReceive = clientSocket.Receive(buffer);
                string receiveStr = Encoding.Default.GetString(buffer, 0, countReceive);
                Console.WriteLine("收到:" + clientName + ":" + receiveStr);
                string[] command = receiveStr.Split(',');

                string fileName = null;
                long fileLength = -1L;

                if (command[0] == "nameAndLength")
                {
                    fileName = command[1];
                    fileLength = long.Parse(command[2]);
                    clientSocket.Send(Encoding.Default.GetBytes("ok"));
                    Console.WriteLine("接收文件:" + fileName + " 请等候……");

                    long recieved = 0L;

                    using (FileStream fsWriter = new FileStream(Path.Combine(_path, fileName), FileMode.Create, FileAccess.Write, FileShare.None))
                    {
                        int recive;

                        while (recieved < fileLength)
                        {
                            recive = clientSocket.Receive(buffer);
                            fsWriter.Write(buffer, 0, recive);
                            fsWriter.Flush();
                            recieved += recive;
                            Console.WriteLine("已接收数据:{0}/{1}", recieved.ToString(), fileLength.ToString());
                        }

                        Console.WriteLine("接收完成……\n");
                    }
                }
            }
        }
        catch (Exception)
        {
            Console.WriteLine("客户端:" + clientName + "退出");
        }
    }
}

}
客户端:

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

namespace Client
{
class Program
{
private static Socket _sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

    /*exe 127.0.0.1 8080 D:\\*/
    static void Main(string[] args)
    {
        int port = int.Parse(args[1]);
        string path = args[2];
        _sock.Connect(new IPEndPoint(IPAddress.Parse(args[0]), port));
        Console.WriteLine("连接成功…");
        bool firstFlag = true;

        while (true)
        {
            if (!firstFlag)
            {
                Console.WriteLine("请输入需要发送的文件路径:");
                path = Console.ReadLine();
            }

            try
            {
                using (FileStream fsReader = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.None))
                {
                    long sended = 0L;
                    long fileLength = fsReader.Length;
                    string fileName = Path.GetFileName(path);
                    string sendStr = "nameAndLength," + fileName + "," + fileLength.ToString();

                    _sock.Send(Encoding.Default.GetBytes(sendStr));

                    const int BUFFERSIZE = 1024 * 1024;
                    byte[] buffer = new byte[32];

                    int recvCount = _sock.Receive(buffer);
                    string mes = Encoding.Default.GetString(buffer, 0, recvCount);

                    if (mes == "ok")
                    {
                        Console.WriteLine("发送文件:" + fileName + " 请等待……");
                        byte[] fileBuffer = new byte[BUFFERSIZE];

                        int readCount;
                        int sending;
                        int readCountLeft;

                        while ((readCount = fsReader.Read(fileBuffer, 0, BUFFERSIZE)) != 0)
                        {
                            sending = 0;
                            readCountLeft = readCount;
                            while ((sending += _sock.Send(fileBuffer, sending, readCountLeft, SocketFlags.None)) < readCount) // 判断发送完
                            {
                                readCountLeft = readCount - sending;
                            }
                            sended += sending;
                            Console.WriteLine("发送数据:{0}/{1}", sended.ToString(), fileLength.ToString());
                        }

                        Console.WriteLine("发送完毕……\n");
                        firstFlag = false;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}

}

标签:Console,Socket,C#,System,传输,WriteLine,new,using,string
From: https://www.cnblogs.com/caoyi21/p/18159227

相关文章

  • dotnet 简单方法在一个进程内同时跑起 WPF 和 ASP.NET Core 框架
    从设计架构上,无论是WPF还是ASP.NETCore框架,都是在dotnet运行时上层的应用,两个框架处于平级的结构。理论上讲,两个平级的框架只要不存在特殊的情况,都是能够相容存在的。本文将和大家介绍一个非常简单的方法,在一个进程内同时跑起WPF和ASP.NETCore框架在一个进程内同时跑......
  • 他又来了,.net开源智能家居之小米米家的c#原生sdk【MiHome.Net】1.0.0发布,快来打造你的
    背景介绍hi大家好,我是三合,作为一个非著名懒人,智能家居简直刚需,在上一篇文章他来了他来了,.net开源智能家居之苹果HomeKit的c#原生sdk【Homekit.Net】1.0.0发布,快来打造你的私人智能家居吧中有靓仔提到,没有苹果设备,有一说一,苹果手机很贵,并且原生支持苹果HomeKit的智能家居设备也......
  • pyclipper的多边形操作(转载)
    等距离缩放多边形:参考博客:https://blog.csdn.net/jizhidexiaoming/article/details/134435885 文本检测DBnet中对标签的预处理里面需要用到这个操作:将文本标注框等距离缩放用于生成标签二值图像和阈值图像,如下所示: 备注:上图出自Dbnet论文原来python有个库pyclipper自带这......
  • Windows下RocketMQ的启动
    下载地址:下载|RocketMQ 解压后   一、修改runbroker.cmd修改 bin目录下的runbroker.cmdset"JAVA_OPT=%JAVA_OPT%-server-Xms2g-Xmx2g"set"JAVA_OPT=%JAVA_OPT%-XX:MaxDirectMemorySize=15g"set"JAVA_OPT=%JAVA_OPT%-cp%CLASSPATH%"分别改为 s......
  • Docker - 基本概念、与虚拟机的区别、架构、镜像操作、容器操作、数据卷挂载
    Docker-基本概念、与虚拟机的区别、架构、镜像操作、容器操作、数据卷挂载 一、对Docker 的理解1、Docker基本概念我们平时开发大型项目组件较多,依赖关系复杂,环境差异大,通过Docker就可解决上述问题~ Docker就是一个快速交付应用、运行应用的技术:运行前后:......
  • dotnet C# 使用 Win32 函数获取用户下载文件夹的路径的方法
    大家都知道,在dotnet里面的可以使用Environment.GetFolderPath方法配合Environment.SpecialFolder枚举列出当前运行环境下的一些特殊文件夹。然而SpecialFolder枚举不包含对Download下载文件夹的枚举值,如咱需要获取用户当前的下载文件夹,需要使用Win32方法来辅助获取在......
  • 什么是 Docker?Docker详解,7分钟学会
    Docker容器是一种打包格式,可通过标准格式打包应用的所有代码和依赖关系,确保应用能够快速、可靠地在计算环境下运行。Docker容器是一种广受欢迎的轻量级、可执行的独立容器,其中包含应用运行所需的一切要素,包括库、系统工具、代码和运行时。此外,Docker还是一个软件平台,支持开发人......
  • 使用 ForAttributeWithMetadataName 提高 IIncrementalGenerator 增量 Source Generat
    本文将告诉大家如何使用ForAttributeWithMetadataName方法用来提高IIncrementalGenerator增量SourceGenerator源代码生成的开发效率以及提高源代码生成器的运行效率这是一个在2022的6月15才合入的新功能。原因是Roslyn团队发现了大量的源代码生成器和分析器项目都......
  • linux(麒麟 centos7)安装7z
    1、下载7-Zip下载地址:7-Zip-程序下载  2、解压mkdir7zip--创建文件夹7zipmv7z2301-linux-x64.tar.xz7zip/--移动cd7ziptar-xvJf7z2301-linux-x64.tar.xz--解压输入ll查看解压后的文件3、安装cp7zzs/usr/local/bin/输入7zzs查看是否安装成功4......
  • Nginx 配置文件 nginx.conf
    #帮助限制Nginx进程的权限,从而减少系统遭受恶意攻击的风险#通常,出于安全考虑,推荐不使用root用户运行网络服务#user<username>[groupname];#设置Nginx将启动的工作进程数目(默认为1)#worker_processes7;#可以填数字#worker_processesauto;#auto代表......