无法通过TCP

时间:2019-02-25 10:53:44

标签: c# .net tcp tcpclient tcplistener

我正在研究一个通过TCP传输文件的项目。它是用.NET 4.7编写的。客户端在同一台计算机上的服务器上连接时,该程序可以运行,但是当我将其发送给朋友并尝试连接它时,出现错误:

  

连接尝试失败是因为被连接方在一段时间后未正确响应,或者由于连接的主机未能响应而建立的连接失败

当前,该程序仅发送一些有关将被复制的文件的信息,没有任何内容被加密,因为我什至无法发送这些信息。

这是服务器的代码(使用Invoke是因为它在单独的线程上运行):

    private void Server_Start()
    {


        try
        {
            // Set port on 13000
            int port = 13000;

            //Get the ip adress for the server
            String localIp;

            using (var client = new WebClient())
            {
                // Try connecting to Google public DNS and get the local endpoint as IP
                // If failed to connect set IP as local IP
                if (CheckForInternetConnection())
                {
                    try
                    {
                        using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, 0))
                        {
                            socket.Connect("8.8.8.8", 65530);
                            IPEndPoint endPoint = socket.LocalEndPoint as IPEndPoint;
                            localIp = endPoint.Address.ToString();
                        }
                    }
                    catch (Exception e)
                    {
                        localIp = "127.0.0.1";
                    }
                }
                else
                {
                    localIp = "127.0.0.1";
                }
            }


            IPAddress IP = IPAddress.Parse(localIp);

            // Create listener and start listening 
            server = new TcpListener(IP, port);
            server.Start();

            // Buffer for data
            Byte[] bytes = new byte[256];
            String data = string.Empty;
            this.Invoke((MethodInvoker)(() => Log.Items.Add("Server started on ip: " + IP.ToString())));
            while (true)
            {

                // Accepting requests
                TcpClient client = server.AcceptTcpClient();

                // Get the stream object
                NetworkStream stream = client.GetStream();

                // Read length of file name
                byte[] nameLength = new byte[4];
                stream.Read(nameLength, 0, 4);
                int nameSize = BitConverter.ToInt32(nameLength, 0);

                // Read the name of file
                byte[] name = new byte[nameSize];
                stream.Read(name, 0, nameSize);
                String fileName = Encoding.UTF8.GetString(name);

                // Read size of file
                byte[] fileSizeB = new byte[4];
                stream.Read(fileSizeB, 0, 4);
                int fileSize = BitConverter.ToInt32(fileSizeB, 0);

                // Read start signal
                byte[] startB = new byte[9+1];
                stream.Read(startB, 0, 9);
                String start = Encoding.UTF8.GetString(startB);

                this.Invoke((MethodInvoker)(() => Log.Items.Add("Size of name: " + nameSize.ToString())));
                this.Invoke((MethodInvoker)(() => Log.Items.Add("Name of file: " + fileName)));
                this.Invoke((MethodInvoker)(() => Log.Items.Add("File size: " + fileSize.ToString())));
                this.Invoke((MethodInvoker)(() => Log.Items.Add("Start signal: " + start)));

                // Response to client
                byte[] message = Encoding.UTF8.GetBytes("Testmessage");
                stream.Write(message, 0, message.Length);
            }
            server.Stop();
            Log.Items.Add("Server started on ip: " + IP.ToString());
        }
        catch (Exception e)
        {
            this.Invoke((MethodInvoker)(() => Log.Items.Add(e)));
        }

    }

这是客户端的代码:

    private void button1_Click(object sender, EventArgs e)
    {
        IPAddress iP = IPAddress.Parse(ConnectIp.Text);
        int port = 13000;
        int buffersize = 1024;

        TcpClient client = new TcpClient();
        NetworkStream netStream;

        // Try to connect to server
        try
        {
            client.Connect(new IPEndPoint(iP, port));
        }
        catch(Exception ex)
        {
            this.Invoke((MethodInvoker)(() => Log.Items.Add(ex.Message)));
            return;
        }

        netStream = client.GetStream();

        String path = "D:\\testingEnv\\test1\\testing\\Matematika\\2017\\Školsko\\2017-SS-skolsko-B-1234-zad.pdf";

        String Filename = Path.GetFileName(path);

        // We wish to send some data in advance:
        // File name, file size, number of packets, send start and send end

        byte[] data = File.ReadAllBytes(path);

        // First packet contains: name size, file name, file size and "sendStart" signal
        byte[] nameSize = BitConverter.GetBytes(Encoding.UTF8.GetByteCount(Filename)); // Int
        byte[] nameB = Encoding.UTF8.GetBytes(Filename);
        byte[] fileSize = BitConverter.GetBytes(data.Length);
        byte[] start = Encoding.UTF8.GetBytes("sendStart");

        // Last packet constains: "sendEnd" signal to stop reading netStream
        byte[] end = Encoding.UTF8.GetBytes("sendEnd");

        // Creating the first package: nameSize, fileName, fileSize and start signal
        byte[] FirstPackage = new byte[4 + nameB.Length + 4 + 9];
        nameSize.CopyTo(FirstPackage, 0);
        nameB.CopyTo(FirstPackage, 4);
        fileSize.CopyTo(FirstPackage, 4 + nameB.Length);
        start.CopyTo(FirstPackage, 4 + nameB.Length + 4);

        // Send the first pckage
        netStream.Write(FirstPackage, 0, FirstPackage.Length);

        byte[] buffer = new byte[30];

        // Read the response
        netStream.Read(buffer, 0, 11);

        netStream.Close();



        client.Close();
    }

一个朋友试图将端口13000进行端口转发,但是它也不起作用。我们甚至尝试过关闭防火墙,但一无所获。我在互联网上搜索,但找不到解决该问题的任何方法。

要注意的一件事是两个函数都在同一应用程序中。我不知道这是否是问题的原因。

有人知道这是怎么回事吗?

预先感谢

1 个答案:

答案 0 :(得分:0)

您是否尝试过使用telnet连接到服务器? “ telnet localhost 13000”或来自具有正确IP和地址nbr的其他计算机?调试服务器代码时,请尝试该操作。如果telnet有效,则客户端代码有问题。.