无法通过TCP连接到另一台计算机

问题描述 投票:0回答:1

我正在开发一个通过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端口,但它也没有用。我们甚至尝试过防火墙没什么问题。我在互联网上搜索但找不到任何问题的解决方案。

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

有谁知道这里有什么问题?

提前致谢

c# .net tcp tcpclient tcplistener
1个回答
0
投票

您是否尝试使用telnet连接到服务器? “telnet localhost 13000”或来自其他计算机的正确IP和地址nbr?在调试服务器代码时尝试这样做。如果telnet工作,那么客户端代码有一些问题..

© www.soinside.com 2019 - 2024. All rights reserved.