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)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 联想st510开卡软件_无力吐槽的一单联想ST510固态硬盘数据恢复

    联想st510开卡软件_无力吐槽的一单联想ST510固态硬盘数据恢复接苏州IT服务商客户送修一块联想ST510固态硬盘需要恢复数据,故障现象为SSD可以正常识别,而且识别的速度也是很快的!,我们接上PC3000访问第一扇区显示代码是错误的,然后读取其它扇区就BSY状态了,必须从新断电加电才可以读取!(从经验判断这块SSD的主控应该是SM2258XT或SM2256K,PC3000SSD加载恢复的速度正常是8M每秒左右)由于这块硬盘转手次数太多(起码转了4手)也没…

    2022年9月2日
    3
  • Tomcat问题集锦

    Tomcat问题集锦Tomcat问题集锦

    2022年4月24日
    35
  • linux如何退出编辑状态_linux编辑文件命令 vi

    linux如何退出编辑状态_linux编辑文件命令 vilinux退出编辑模式的命令linux退出编辑模式的命令有:vim有三种模式,注意:这三种模式有很多不同的叫法,我这里是按照鸟哥的linux书中的叫法。一般指令模式、编辑模式、指令列命令模式1.vim文件名进入一般模式;2.按i进行编辑进入编辑模式;(或者I,o,O,a,A,r,R)3.编辑结束,按ESC键跳到一般模式模式;4.按:进入指令列命…

    2022年10月1日
    0
  • pycharm使用gpu运行_降低python程序cpu占用高

    pycharm使用gpu运行_降低python程序cpu占用高本人频繁在pycharm下run程序,经常终止,可能其后台运行的Python程序没有关闭,所以耗尽GPU资源。现象是占用GPU的进场ID为空,即nvidia-smi后,没有进程使用GPU,但每块GPU的内存确被使用很多。。。。。fuser-v/dev/nvidia*会发现很多Python在运行,故粗暴地kill这些进程ID就可以了。。。。。。。ID乍一看很多,杀死一两个就不剩几个了。。。。本方…

    2022年8月29日
    2
  • Idea激活码最新教程2024.2.0.2版本,永久有效激活码,亲测可用,记得收藏

    Idea激活码最新教程2024.2.0.2版本,永久有效激活码,亲测可用,记得收藏Idea 激活码教程永久有效 2024 2 0 2 激活码教程 Windows 版永久激活 持续更新 Idea 激活码 2024 2 0 2 成功激活

    2025年5月28日
    2
  • scrapy安装步骤_scrapy官网

    scrapy安装步骤_scrapy官网安装scrapy过程中出现各种包安装错误,所以自己一直看教程知道scrapy安装需要准备好各种环境。这些包按照从下到上的顺序下载,lxml这个包按下文教程安装。不想看过多文字和图片的懒人们可看教程视频:http://www.iqiyi.com/w_19rz36pjft.html利用pipinstall命令安装pywin32,pyopenssl.这两个包可在cmd安装成功pip…

    2022年9月18日
    0

发表回复

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

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