C#实现一个局域网文件传输工具

C#实现一个局域网文件传输工具工作需要,经常会在工作的台式机和笔记本之间传文件或者需要拷贝文本,两个机器都位于局域网内,传文件或者文本的方式有很多种,之前是通过共享文件夹来进行文件的拷贝,或者通过SVN进行同步。文本传递比较简单,可以通过两台机器上装QQ登两个号码,或者在共享目录下建一个TXT,或者发电子邮件等等。不过上面这些方法总觉得不直接,所以想基于P2P做一个小的局域网文件和文字传输小工具。WinForm的工程,

大家好,又见面了,我是你们的朋友全栈君。

工作需要,经常会在工作的台式机和笔记本之间传文件或者需要拷贝文本,两个机器都位于局域网内,传文件或者文本的方式有很多种,之前是通过共享文件夹来进行文件的拷贝,或者通过SVN进行同步。文本传递比较简单,可以通过两台机器上装QQ登两个号码,或者在共享目录下建一个TXT,或者发电子邮件等等。

不过上面这些方法总觉得不直接,所以想基于P2P做一个小的局域网文件和文字传输小工具

WinForm的工程,界面方面的代码就不贴了,大家自己根据喜好设计就好了,主要把TCP数据传输的代码和逻辑贴出来:

1. 文件和文本传输的通用方法:

private string ReceiveControl(Socket socket)
{
    int bufSize = 1024;
    byte[] buf = new byte[bufSize];
    int len = socket.Receive(buf);
    return len > 0 ? Encoding.UTF8.GetString(buf, 0, len) : String.Empty;
}
private void SendControl(Socket socket, string controlMsg)
{
    byte[] msgBytes = Encoding.UTF8.GetBytes(controlMsg);
    socket.Send(msgBytes);
}
private string ReceiveContent(Socket socket, int contentLen)
{
    int receivedLen = 0;
    int bufSize = 1024;
    byte[] buf = new byte[bufSize];
    StringBuilder sb = new StringBuilder();
    while (receivedLen < contentLen)
    {
        int len = socket.Receive(buf);
        if (len > 0)
        {
            sb.Append(Encoding.UTF8.GetString(buf, 0, len));
            receivedLen += len;
        }
    }
    return sb.ToString();
}
private void SendContent(Socket socket, string content)
{
    byte[] contentBytes = Encoding.UTF8.GetBytes(content);
    SendControl(socket, contentBytes.Length.ToString());
    ReceiveControl(socket);
    socket.Send(contentBytes);
}
private void ReceiveFile(Socket socket, string fileName, int fileLen)
{
    string filePath = Path.Combine(GetCurrentUserDesktopPath(), RenameConflictFileName(fileName));
    using (Stream fs = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite))
    {
        int bufLen = 1024;
        int receivedLen = 0;
        byte[] buf = new byte[bufLen];
        int len = 0;
        while (receivedLen < fileLen)
        {
            len = socket.Receive(buf);
            fs.Write(buf, 0, len);
            receivedLen += len;
        }
    }
}
private void SendFile(Socket socket, string filePath)
{
    using (Stream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
    {
        SendControl(socket, GetFileNameFromPath(filePath));
        ReceiveControl(socket);
        SendControl(socket, fs.Length.ToString());
        ReceiveControl(socket);
        int bufLen = 1024;
        byte[] buf = new byte[bufLen];
        long readLen = 0;
        long fileLen = fs.Length;
        int len = 0;
        while (readLen < fileLen)
        {
            len = fs.Read(buf, 0, bufLen);
            readLen += len;
            int sentLen = 0;
            int realSent = 0;
            int left = 0;
            while (sentLen < len)
            {
                left = len - realSent;
                realSent = socket.Send(buf, sentLen, left, SocketFlags.None);
                sentLen += realSent;
            }
        }
    }
}

2.连接,发送文字/文件,重命名文件等方法:

private void SendText()
{
    if (connected)
    {
        if (!String.IsNullOrEmpty(this.TextToSend.Text))
        {
            string txt = this.TextToSend.Text;
            SendControl(clientSocket, "Text");
            ReceiveControl(clientSocket);
            SendContent(clientSocket, txt);
            ReceiveControl(clientSocket);
        }
    }
}

private void Connect()
{
    try
    {
        if (!connected)
        {
            passive = false;
            IPAddress serverIPAddress = IPAddress.Parse(this.ServerIPAddress.Text);
            clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            clientSocket.Connect(serverIPAddress, 60000);
            string msg = ReceiveControl(clientSocket);
            if (msg.Equals("Connected"))
            {
                this.ConnectBtn.Text = "Disconnect";
                connected = true;
            }
        }
        else
        {
            passive = true;
            SendControl(clientSocket, "Disconnect");
            clientSocket.Close();
            this.ConnectBtn.Text = "Connect";
            connected = false;
        }
    }
    catch (Exception err)
    {
        MessageBox.Show(string.Format("Failed to connect to server, error: {0}", err.ToString()));
    }
}

private void ServerThread()
{
    IPAddress local = IPAddress.Parse("0.0.0.0");
    Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    server.Bind(new IPEndPoint(local, 60000));
    server.Listen(1);
    while (true)
    {
        Socket receivedClientSocket = server.Accept();
        IPEndPoint clientEndPoint = (IPEndPoint)receivedClientSocket.RemoteEndPoint;
        SendControl(receivedClientSocket, "Connected");
        if (passive)
        {
            clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            clientSocket.Connect(clientEndPoint.Address, 60000);
            string msg = ReceiveControl(clientSocket);
            if (msg.Equals("Connected"))
            {
                connected = true;
                this.ConnectBtn.Text = "Disconnect";
                this.ServerIPAddress.Text = clientEndPoint.Address.ToString();
            }
        }
        while (connected)
        {
            string msg = ReceiveControl(receivedClientSocket);
            switch (msg)
            {
                case "Disconnect":
                    receivedClientSocket.Close();
                    clientSocket.Close();
                    this.ConnectBtn.Text = "Connect";
                    passive = true;
                    connected = false;
                    break;
                case "Text":
                    SendControl(receivedClientSocket, "Received");
                    int length = Convert.ToInt32(ReceiveControl(receivedClientSocket));
                    SendControl(receivedClientSocket, "Received");
                    string content = ReceiveContent(receivedClientSocket, length);
                    SendControl(receivedClientSocket, "Received");
                    this.TextToSend.Text = content;
                    break;
                case "File":
                    SendControl(receivedClientSocket, "Received");
                    string fileName = ReceiveControl(receivedClientSocket);
                    SendControl(receivedClientSocket, "Received");
                    int fileLen = Convert.ToInt32(ReceiveControl(receivedClientSocket));
                    SendControl(receivedClientSocket, "Received");
                    ReceiveFile(receivedClientSocket, fileName, fileLen);
                    SendControl(receivedClientSocket, "Received");
                    MessageBox.Show("File Received");
                    break;
            }
        }
    }
}

private string GetFileNameFromPath(string path)
{
    int index = path.LastIndexOf('\\');
    return path.Substring(index + 1);
}

private string RenameConflictFileName(string originalName)
{
    string desktopPath = GetCurrentUserDesktopPath();
    int extensionIndex = originalName.LastIndexOf(".");
    string fileName = originalName.Substring(0, extensionIndex);
    string extensionName = originalName.Substring(extensionIndex + 1);

    int renameIndex = 1;
    string newNameSuffix = String.Format("({0})", renameIndex);
    string finalName = originalName;
    string filePath = Path.Combine(desktopPath, finalName);
    if (File.Exists(filePath))
    {
        finalName = String.Format("{0} {1}.{2}", fileName, newNameSuffix, extensionName);
        filePath = Path.Combine(desktopPath, finalName);
    }
    while (File.Exists(filePath))
    {
        renameIndex += 1;
        string oldNameSuffix = newNameSuffix;
        newNameSuffix = String.Format("({0})", renameIndex);
        finalName = finalName.Replace(oldNameSuffix, newNameSuffix);
        filePath = Path.Combine(desktopPath, finalName);
    }

    return finalName;
}

private string GetCurrentUserDesktopPath()
{
    return Environment.GetFolderPath(System.Environment.SpecialFolder.Desktop);
}

运行截图:

C#实现一个局域网文件传输工具

完整代码可以到下面的地址下载:

http://download.csdn.net/detail/qwertyupoiuytr/9895436


版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/136239.html原文链接:https://javaforall.net

(0)
上一篇 2022年6月3日 下午10:16
下一篇 2022年6月3日 下午10:16


相关推荐

  • linux的vi命令详解_centos7 vi命令

    linux的vi命令详解_centos7 vi命令Linux命令-vi命令  vi编辑器是所有Unix及Linux系统下标准的编辑器,它的强大不逊色于任何最新的文本编辑器.由于对Unix及Linux系统的任何版本,vi编辑器是完全相同的,因此您可以在其他任何介绍vi的地方进一步了解它。Vi也是Linux中最基本的文本编辑器.。1.语法:vi[参数][文件名称]…2.功能:  编辑文件。3.参数:n打印最近的n条历史命令。-N显示历史记录中最近的N个记录。-c清空当前历史命令。-a将目前新增的历史

    2026年2月16日
    5
  • 计算机网络重点回顾

    计算机网络一.计算机网络概述计算机网络的概念:(*)1.计算机网络的定义:​ 计算机网络是指将地理位置不同的具有独立功能的多台计算机及其外部设备,通过通信线路链接起来,在网络操作系统,网络管理软件及网络通信协议的管理和协调下,实现资源共享和信息传递的计算机系统。2.计算机网络的组成:终端系统/资源子网:提供共享的软件资源和硬件资源通信子网:提供信息交换的网络结点和通信线路。3.计算机网络的类型:按照拓朴分类:星型结构树形结构总线型结构环形结构网状结构按照范围分

    2022年4月9日
    44
  • SaveFileDialog_save文件用什么修改

    SaveFileDialog_save文件用什么修改c#获取要保存文件的对话框,用SaveFileDialog类。具体用法很简单分享一下吧,对于初学者可能有用//可能要获取的路径名stringlocalFilePath=“”,fileNameExt=“”,newFileName=“”,FilePath=“”;SaveFileDialogsaveFileDialog=newSaveFileDialog();//设置文件类型//书写规则例如:txtfiles(.txt)|.txtsaveFileDialog.Filter

    2022年10月8日
    5
  • PyCharm和git安装教程

    PyCharm和git安装教程先到官网下载 githttps git scm com download win 进入 setting 如黄色部分如果你用的是 github 那么直接 setting 登陆就行了如果你是 gitee 的话首先进入 setting 然后 Plugins 点击 browse 查找 gitee 如图所示 最后点击重启 ok 不要自己关闭 否则安装失败 安装好了以后 这里走了一些弯路省去不写 直接写正确答案 根据经验

    2026年3月27日
    1
  • mediumtext_text长度不够用,改为mediumtext感觉 又太大,有没什么方法?

    mediumtext_text长度不够用,改为mediumtext感觉 又太大,有没什么方法?楼主先要搞清楚,text和longtext这些都是可变长度的字段类型.这是phpMyAdmin里的说明:text:最多存储65535(2^16-1)字节的文本字段,存储时在内容前使用2字节表示内容的字节数.longtext:最多存储4294967295字节即4GB(2^32-1)的文本字段,存储时在内容前使用4字节表示内容的字节数.也就是说,你在longtext类型的字段里只存1个字符,占用空…

    2022年5月1日
    82
  • 刘润年度演讲2021:进化的力量(演讲全文)

    刘润年度演讲2021:进化的力量(演讲全文)周六通过直播看了刘润老师的演讲 不得不说 刘润老师是真的牛逼 五个小时的演讲 没喝过一口水 没去过一次厕所 就这份耐力就非常人 没人不辛苦 只是有人不说疼 以下是刘润老师 2021 年

    2026年3月17日
    2

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号