首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >TcpClient挂起

TcpClient挂起
EN

Stack Overflow用户
提问于 2018-03-16 03:52:02
回答 1查看 453关注 0票数 0

我正在开发一个简单的客户端,将数据发送到我办公室的服务器。我用一台名为TCPServer的服务器在我的计算机上本地测试代码,我连接、发送数据、接收回复、断开连接、再次发送、漂洗和重复,它们都工作得很完美,但是当我连接到办公室并做同样的连接时,我可以永远连接/断开连接,但是当我发送数据时它只是挂起。办公室的日志里没有收到任何东西。我不能在那里发送一个字节。

好像是防火墙问题,不是吗。

但是我可以运行我几年前用Delphi (pascal)编写的一个旧程序,它可以在没有问题、相同端口和所有东西的情况下连接和发送相同的数据,所以问题不是防火墙问题。对此有什么想法吗?下面是基本的代码布局。

连接按钮断开按钮发送按钮

在类的顶部,我声明了TcpClient变量

代码语言:javascript
复制
    public TcpClient m_client = new TcpClient();

在_Click中用于连接按钮和断开按钮,我有代码连接到服务器,并设置了一些指示器等

代码语言:javascript
复制
    private void ConnectButton_Click(object sender, EventArgs e)
    {
        string address = FixIP(IPAddressMaskedTextBox.Text);
        int Port = Convert.ToInt32(PortNumberMaskedTextBox.Text);

        Control control = (Control)sender;
        String name = control.Name;
        try
        {
            switch (name)
            {
                case ("ConnectButton"):
                    //Connect to server
                    connect(address, Port);
                    if (m_client.Connected)
                    {
                        SingleConnectionRichTextBox.Clear();

                        ConnectedLightButton.BackColor = Color.Lime;
                        SingleConnectionRichTextBox.Text += "Connected at IP " + address + " and Port " + Port.ToString() + "\r\n";
                    }
                    break;
                case ("DisconnectButton"):
                    if (m_client.Connected)
                    {
                        SingleConnectionRichTextBox.Text += "Connection Terminated\r\n";
                        ConnectedLightButton.BackColor = Color.Red;
                        m_client.Client.Disconnect(false);
                        m_client = new TcpClient();
                    }
                    break;
            }
        }
        catch (Exception err)
        {
            MessageBox.Show(err.ToString());
        }
    }

    public void connect(string address, int port)
    {
        try
        {
            if (!m_client.Connected)
            {
                ConnectedLightButton.BackColor = Color.Yellow;
                SingleConnectionRichTextBox.Text += "Attempting to Connect...\r\n";
                m_client.Connect(address, port);
            }
            else
            {
                SingleConnectionRichTextBox.Text += "Connection Failed...\r\n";
                ConnectedLightButton.BackColor = Color.Red;
                throw new Exception("Connect: Already connected\r\n");
            }
        }
        catch (Exception err)
        {
            MessageBox.Show(err.ToString());
        }
    }

发送按钮有它自己的事件,主要是因为当连接到office时,创建套接字需要一分钟时间,等等,

代码语言:javascript
复制
    private void SendButton_Click(object sender, EventArgs e)
    {
        try
        {
            if (m_client.Connected)
            {
                string completeString = "";

                for (int cnt = 0; cnt < SingleSendRichTextBox.Lines.Count() - 1; cnt++)
                {
                    string aLine = Regex.Replace(SingleSendRichTextBox.Lines[cnt], @"\e\[(\d+;)*(\d+)?[ABCDHJKfmsu]", "");

                    if (cnt == 0)
                    {
                        //First line gets Start Block, plus a CR on end
                        aLine = (char)0x0B + aLine + (char)0x0D;
                    }
                    else if (cnt == (SingleSendRichTextBox.Lines.Count() -1))
                    {
                        //Last line gets CR + End Block + CR on end
                        aLine += (char)0x0D + (char)0x1C + (char)0x0D;
                    }
                    else
                    {
                        //All middle lines get CR on end
                        aLine += (char)0x0D;
                    }

                    //MessageBox.Show("Sending line# " + cnt.ToString() + " = " + aLine);
                    completeString += aLine;
                }
                Byte[] data = Encoding.ASCII.GetBytes(completeString);
                WriteBytes(data);
                ReadAllBytes();
            }
            else
            {
                MessageBox.Show("Nothing is connected currently...");
            }
        }
        catch (Exception err)
        {
            MessageBox.Show(err.ToString());
        }
    }

    public void WriteBytes(Byte[] data)
    {
        try
        {
            if ((m_client.Connected)&&(data.Count() > 0))
            {
                // Get access to network stream
                NetworkStream stm = m_client.GetStream();

                stm.Write(data, 0, data.Length);
                stm.Flush();

                //MessageBox.Show("Data Sent, length = " + data.Length.ToString());
            }
            else
            {
                MessageBox.Show("Either we are not connected, or there is no data to send!!");
            }
        }
        catch (Exception err)
        {
            MessageBox.Show(err.ToString());
        }
    }

    public void ReadAllBytes()
    {
        try
        {
            // Buffer to store the response bytes.
            Byte[] readdata = new Byte[256];

            // String to store the response ASCII representation.
            String responseData = String.Empty;

            NetworkStream stm = m_client.GetStream();

            // Read the first batch of the TcpServer response bytes.
            Int32 bytes = stm.Read(readdata, 0, readdata.Length);
            responseData = Encoding.ASCII.GetString(readdata, 0, bytes);
            SingleReplyRichTextBox.Text += responseData + "\r\n";
        }
        catch (Exception err)
        {
            MessageBox.Show(err.ToString());
        }
    }

这里有什么明显的红旗吗?我尝试过Stream。我试着关掉回复听者。我将这些代码合并到一个函数中,并将TcpClient创建作为静态迁移到一个不同的类,这样我就可以在每个函数中创建它,但是尽管所有这些都在本地很好地工作,但是没有任何东西可以连接到office。它不会发送一个字节。我把m_client设置为顶部是静态的,在本地工作很好,而不是去办公室。

GetStream可能会失败吗?还是将数据发送到不同的套接字上?

EN

回答 1

Stack Overflow用户

发布于 2018-11-11 15:02:04

使用任务和取消令牌取消任务。不要在一个“新的”TCPclient。在后台,TCPclient将不会关闭(.net的套接字超时),使用尝试捕获来查看异常,并将日志添加到会话中以使其更加清晰。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49312916

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档