通过 TCP/IP 将 .txt 文件从一台计算机简单发送到另一台计算机 [英] Simple sending .txt file from one computer to another via TCP/IP

查看:46
本文介绍了通过 TCP/IP 将 .txt 文件从一台计算机简单发送到另一台计算机的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有两个 C# 项目:一个项目用于客户端,另一个用于服务器.第一步是运行服务器,然后选择一个目标文件夹,然后运行客户端项目,选择一些 text.txt 发送到服务器的目标文件夹.只有客户端可以向服务器发送文件

演示:

1.choosing file target 2.client 发送+------------+|tar 文件夹 |<---------------- 文本.txt+------------+

我的问题: 两个项目都没有编译错误或语法错误,唯一的问题是服务器没有收到 .txt 文件.

客户:

首先我为客户设计了一个表格,例如:

并从 ToolBox-> Dialogs-> OpenFileDialog 控件中放置一个 OpenFileDialog.

完整代码:

命名空间 SFileTransfer{公共部分类 Form1 :表单{字符串 n;字节[] b1;OpenFileDialog op;private void button1_Click(object sender, EventArgs e)//browse btn{op = new OpenFileDialog();如果 (op.ShowDialog() == DialogResult.OK){字符串 t = textBox1.Text;t = op.FileName;FileInfo fi = new FileInfo(textBox1.Text = op.FileName);n = fi.Name + "."+ fi.长度;TcpClient 客户端 = new TcpClient("127.0.0.1", 8100);//"127.0.0.1", 5055StreamWriter sw = new StreamWriter(client.GetStream());sw.WriteLine(n);sw.flush();//label2.Text = "文件传输....";}}private void button2_Click(object sender, EventArgs e)//发送 btn{TcpClient 客户端 = new TcpClient("127.0.0.1", 8100);//5050流 s = client.GetStream();b1 = File.ReadAllBytes(op.FileName);s.Write(b1, 0, b1.Length);客户端.关闭();//label2.Text = "文件传输....";}}}

服务器:

为服务器创建并设计了一个表单,例如:

然后从 ToolBox->Dialogs->folderBrowserDialog 放置一个 folderBrowserDialog.

完整代码:

命名空间 SFileTransferServer{公共部分类 Form1 :表单{字符串 rd;字节[] b1;字符串 v;整数 m=1;TcpListener 列表;TcpClient 客户端;int32 端口 = 8100;//5050int32 port1 = 8100;//5055IPAddress localAddr = IPAddress.Parse("127.0.0.1");private void button1_Click(object sender, EventArgs e)//浏览按钮{如果(folderBrowserDialog1.ShowDialog() == DialogResult.OK){textBox1.Text = folderBrowserDialog1.SelectedPath;list = new TcpListener(localAddr, port1);list.Start();客户端 = list.AcceptTcpClient();MessageBox.Show("ggggggg" + m.ToString());流 s = client.GetStream();b1 = 新字节[m];s.Read(b1, 0, b1.Length);MessageBox.Show(textBox1.Text);File.WriteAllBytes(textBox1.Text+ "\\" + rd.Substring(0, rd.LastIndexOf('.')), b1);列表.停止();客户端.关闭();label1.Text = "文件收到......";}}private void Form2_Load(对象发送者,EventArgs e){TcpListener list = new TcpListener(localAddr, port);list.Start();TcpClient 客户端 = list.AcceptTcpClient();MessageBox.Show("客户端尝试连接");StreamReader sr = new StreamReader(client.GetStream());rd = sr.ReadLine();v = rd.Substring(rd.LastIndexOf('.') + 1);m = int.Parse(v);列表.停止();客户端.关闭();}}}

基于此页面

解决方案

我假设你是一个新的编码员,因为我看到了很多低效的代码.

在客户端应用程序上:不要重新声明 TcpClient,而是在全局范围内声明它并重用它.

然后在服务器端:如果可能的话,总是使用正确的数据类型

Int16 端口 = 8100;//与...一样int 端口 = 8100;

然后回到问题:首先,您只从接收到的数据中读取一个字节

int m=1;字节[] b1 = 新字节[m];s.Read(b1, 0, b1.Length);//那么如果你知道字节的长度,为什么要计算b1.Length,就用s.Read(b1, 0, 1);

我现在看到您也在打开 Load 事件的连接.但该变量不在全局范围内,因此您实际上是在 Load 事件中创建一个变量,然后在 Load 事件完成后,将其发送到垃圾收集器,然后在按钮单击事件中声明一个同名变量.

因此尝试在全局范围内声明 TcpListener 对象,然后在加载事件中分配它并开始侦听.

现在 AcceptTcpClient() 方法是一个阻塞方法,因此它将阻塞您的 thead,直到它收到连接尝试,此时它将返回客户端对象.所以尝试改用这个:https:///msdn.microsoft.com/en-us/library/system.net.sockets.tcplistener.accepttcpclient(v=vs.110).aspx

使用 System.Threading;TcpClient 客户端;TcpListener 服务器 = new TcpListener("127.0.0.1",8100)线程incoming_connection = new Thread(ic);传入_connection.Start();私人无效ic(){客户端 = server.AcceptTcpClient();流 s = client.GetStream();//然后是所有其他代码}

或者您可以使用 MSDN 建议的 Pending 方法(在参考页面上).

像这样使用线程'不安全',所以如果你不理解线程,请先阅读它,这篇文章不包括如何使用多线程.

There are two C# projects: one project is for the client, the other one is for the server. First step is to run the server , then to choose a target folder, after that to run the client project, to choose some text.txt to send to the server's target folder. Only client can send files to the server

Demo:

1.choosing file target                       2.client sends
   +------------+                                
   | tar folder |          <----------------       text.txt 
   +------------+

My problem: there isn't compile errors or syntax errors in both projects, the only problem is that the server doesn't receives the .txt file.

Client:

First I designed a form for the client such as:

And placed an OpenFileDialog from the ToolBox-> Dialogs-> OpenFileDialog control.

Full code:

namespace SFileTransfer
{
    public partial class Form1 : Form
    {
        string n;
        byte[] b1;
        OpenFileDialog op;

        private void button1_Click(object sender, EventArgs e) //browse btn
        {
            op = new OpenFileDialog();
            if (op.ShowDialog() == DialogResult.OK)
            {
                string t = textBox1.Text;
                t = op.FileName;
                FileInfo fi = new FileInfo(textBox1.Text = op.FileName);
                n = fi.Name + "." + fi.Length;
                TcpClient client = new TcpClient("127.0.0.1", 8100);//"127.0.0.1", 5055
                StreamWriter sw = new StreamWriter(client.GetStream());
                sw.WriteLine(n);
                sw.Flush();
               // label2.Text = "File Transferred....";
            }
        }
        private void button2_Click(object sender, EventArgs e) //send btn
        {
            TcpClient client = new TcpClient("127.0.0.1", 8100);//5050
            Stream s = client.GetStream();
            b1 = File.ReadAllBytes(op.FileName);
            s.Write(b1, 0, b1.Length);
            client.Close();
           // label2.Text = "File Transferred....";
        }
    }
}

Server:

Created and designed a Form for Server like:

Then Placed a folderBrowserDialog from the ToolBox->Dialogs-> folderBrowserDialog.

Full code:

namespace SFileTransferServer
{
    public partial class Form1 : Form
    {
        string rd;
        byte[] b1;
        string v;
        int m=1;
        TcpListener list;
        TcpClient client;
        Int32 port = 8100;//5050
        Int32 port1 = 8100;//5055
        IPAddress localAddr = IPAddress.Parse("127.0.0.1");

        private void button1_Click(object sender, EventArgs e) //browse button
        {

            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                textBox1.Text = folderBrowserDialog1.SelectedPath;

                list = new TcpListener(localAddr, port1);
                list.Start();

                client = list.AcceptTcpClient();
                MessageBox.Show("ggggggg" + m.ToString());
                Stream s = client.GetStream();
                b1 = new byte[m];

                s.Read(b1, 0, b1.Length);
                MessageBox.Show(textBox1.Text);
                File.WriteAllBytes(textBox1.Text+ "\\" + rd.Substring(0, rd.LastIndexOf('.')), b1);
                list.Stop();
                client.Close();
                label1.Text = "File Received......";
            }
        }
        private void Form2_Load(object sender, EventArgs e)
        {
            TcpListener list = new TcpListener(localAddr, port);
            list.Start();

            TcpClient client = list.AcceptTcpClient();
            MessageBox.Show("Client trying to connect");
            StreamReader sr = new StreamReader(client.GetStream());
            rd = sr.ReadLine();
            v = rd.Substring(rd.LastIndexOf('.') + 1);
            m = int.Parse(v);
            list.Stop();
            client.Close();
        }
    }
}

Based on this page

解决方案

I'm assuming you are a new coder because I'm seeing a lot of inefficient code.

On the Client App: Don't redeclare the TcpClient, instead declare it in the global scope and just reuse it.

Then On the server side: Always use the correct datatype IF AT ALL possible

Int16 port = 8100;
//same as
int port = 8100;

Then on to the question: First you are only reading a single byte from the received data

int m=1;
byte[] b1 = new byte[m];
s.Read(b1, 0, b1.Length);
//Then if you know the length of the byte, why do the computation of b1.Length, just use
s.Read(b1, 0, 1);

I see now you are also opeing the connection on the Load event. But that variable is not in the global scope so you are essentially creating a variable in the Load event then after the Load event finishes, sending it to the garbage collection and then declaring a variable with the same name in the button click event.

So try declaring the TcpListener object in the global scope then assign it in the load event and start listening.

Now the AcceptTcpClient() method is a blocking method so it will block your thead until it receives a connection attempt at which point it will return the client object. So try to use this instead: https://msdn.microsoft.com/en-us/library/system.net.sockets.tcplistener.accepttcpclient(v=vs.110).aspx

using System.Threading;
TcpClient client;
TcpListener server = new TcpListener("127.0.0.1",8100)
Thread incoming_connection = new Thread(ic);
incoming_connection.Start();

private void ic() {
client = server.AcceptTcpClient();
Stream s = client.GetStream();
//And then all the other code
}

Or you can use the Pending method as suggested by MSDN (on the ref page).

EDIT: using threading like this is 'not safe', so if you don't understand threading go read up on it first, this post doesn't cover how to use multi-threading.

这篇关于通过 TCP/IP 将 .txt 文件从一台计算机简单发送到另一台计算机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆