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


相关推荐

  • SAP WebIDE里OData service catalog的实现原理「建议收藏」

    SAP WebIDE里OData service catalog的实现原理「建议收藏」我们在SAPWebIDE里创建UI5应用时,可以从Servicecatalog里选择需要的OData服务,如下图所示:这个ag3-backend是什么意思?是我在SAPCloudPlatform的Destination标签页里维护的一个Destination:这个destination指向了一个OnpremiseABAPNetweaver系统,AG3,通过SAPCloud…

    2022年10月18日
    3
  • ajax跨域的解决办法_java如何解决跨域问题

    ajax跨域的解决办法_java如何解决跨域问题什么是跨域问题?跨域问题来源于JavaScript的”同源策略”,即只有协议+主机名+端口号(如存在)相同,则允许相互访问。也就是说JavaScript只能访问和操作自己域下的资源,不能访问和操作其他域下的资源。跨域问题是针对JS和ajax的,html本身没有跨域问题。查看浏览器开发者工具Console报错:Failedtoloadhttp://a.a.com:8080/A/FromServlet?userName=123:No‘Access-Control-Allow-Origin’

    2022年8月24日
    4
  • 将CSV的数据发送到kafka(java版)

    将CSV的数据发送到kafka(java版)

    2020年11月19日
    163
  • 2022年双非上岸北京理工大学软件工程经验

    2022年双非上岸北京理工大学软件工程经验感想很久之前就想写一篇文章来记录自己这段考研的辛苦历程了,感谢这一路陪伴我的朋友对我的鼓励支持,软工今年是前30去校本部,后35名去唐山研究院,软工相比于前几年来说一直在缩招,20年招95个,21年招74个,今年招65个,所以23今年想报的要做好会缩招的准备,我最终是去了唐山研究院,但是这对我本科双非的学生来说已经知足了。今年2022年被称为考研元年,难度可以说是极其高了,想要上岸不容易,从如今考研的形式来看,未来考研将会越来越难,希望学弟学妹们仔细认真的选择院校,可以通过关注一些公众号像王道论坛,

    2022年6月14日
    497
  • 使用srvany.exe将任何程序作为Windows服务运行[通俗易懂]

    使用srvany.exe将任何程序作为Windows服务运行[通俗易懂]srvany.exe是什么?srvany.exe是MicrosoftWindowsResourceKits工具集的一个实用的小工具,用于将任何EXE程序作为Windows服务运行。也就是说srvany只是其注册程序的服务外壳,这个特性对于我们来说非常实用,我们可以通过它让我们的程序以SYSTEM账户启动,或者实现随机器启动而自启动,也可以隐藏不必要的窗口,比如说控制台窗口等等。如何获取

    2022年6月11日
    35
  • s一般怎么称呼自己的m_75.9%的职场人,都不知道怎么称呼自己的领导

    s一般怎么称呼自己的m_75.9%的职场人,都不知道怎么称呼自己的领导包邮送!人力资源制度手册纸质版和电子版23套制度覆盖员工入职到离职各环节82份表格制度配套全面规范附赠电子版可复制可编辑原价49元纸质版+电子版包邮送!!!最后30本!扫码回复【100】立抢!来源:猎聘(ID:liepinwang)作者:放学堵他谁能想到「怎么称呼别人」这样看似简单到不能再简单的问题,居然会成为让职场萌新发懵,甚至打怵的究极难题。不要以为这是什么夸张的说…

    2022年6月23日
    87

发表回复

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

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