无法通过 TCP 连接到另一台计算机 [英] Cannot connect to another computer over TCP

查看:48
本文介绍了无法通过 TCP 连接到另一台计算机的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am working on a project that transfers files over TCP. It is written in .NET 4.7. The program works while the client connects on the server that is on the same computer but when I send it to a friend and I try to connect it I get an error:

连接尝试失败,因为连接方在一段时间后没有正确响应,或者因为连接的主机没有响应而建立连接失败

A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond

目前该程序仅发送有关将被复制的文件的一些信息,并且没有加密,因为我什至无法发送这些信息.

Currently the program only sends some information about the file that will be copied and is nothing is encrypted as I cannot send even these information.

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

Here's the code for the server (Invoke is used because it is run on a separate thread):

    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,但也没有成功.我们甚至尝试关闭防火墙,但没有.我在互联网上搜索,但找不到任何解决问题的方法.

A friend tried to port forward the port 13000 but it didn't work either. We even tried with the firewall being down but nothing. I searched on the internet but couldn't find any solutions to the problem.

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

One thing to note is that both functions are in the same application. I don't know if that is the cause of the problem.

有人知道这里有什么问题吗?

Does anyone know how what is the problem here?

提前致谢

推荐答案

您是否尝试过使用 telnet 连接到您的服务器?telnet localhost 13000"还是来自其他具有正确 IP 和地址 nbr 的计算机?在调试服务器代码时尝试一下.如果 telnet 有效,则客户端代码有问题..

Have you tried to connect to your server with telnet ? "telnet localhost 13000" or from other computer with correct ip and address nbr ? Try that while debugging your server code. If telnet works, then client code has some problem..

这篇关于无法通过 TCP 连接到另一台计算机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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