C#我如何停止tcpClient.Connect()方法时,我已经准备好了节目结束?它只是坐在那里像10秒! [英] C# How do I stop a tcpClient.Connect() process when i'm ready for the program to end? It just sits there for like 10 seconds!

查看:761
本文介绍了C#我如何停止tcpClient.Connect()方法时,我已经准备好了节目结束?它只是坐在那里像10秒!的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的第一个问题之一。每当我退出了该计划,tcpClient.Connect()需要永远关闭。我试过一吨的东西,他们都不上班。



看一看在创建连接()线程,如果客户端尚未连接......我关闭程序,它永远关闭。如果将它连接,它会立即关闭。我知道这可以通过一些超时伎俩来完成,但我已经尝试了几个和他们没有工作。



请如果您可以提供的代码示例。



此外,有没有什么好的教程在那里为C#在读/带缓冲,而不是这个版本只是做masterServer.writeLine()和masterServer编写实际的字节.readline()或者他们都只有高效?



如果你看到任何东西来帮助我改进这个......用一切手段,继续前进。我想教我如何做到这一点,我没有帮助,所以不要让我去上做错了什么,如果你看到它! !谢谢你们

 使用系统; 
使用System.Collections.Generic;
使用System.ComponentModel;
使用System.Data这;
使用System.Drawing中;
使用System.Linq的;
使用System.Text;使用System.Windows.Forms的
;使用System.Net
;使用的System.Net.Sockets
;
使用的System.Threading;
:使用System.IO;

命名空间RemoteClient
{
公共部分Form1类:表格
{
私人INT MyPort上= 56789;
私人ip地址MYIP = IPAddress.Parse(210.232.115.79);
私人ip地址SERVERIP = IPAddress.Parse(72.216.18.77); //主服务器的IP地址
公共静态的TcpClient masterServer =新的TcpClient();

私人的StreamWriter responseWriter;
私人的StreamReader commandReader;

私人螺纹connectionThread;
私人螺纹commandsThread;

私人布尔RequestExitConnectionThread {搞定;组; }

私人委托无效AddMessageDelegate(字符串消息,INT类);
私人委托无效ConnectedDelegate();

私人BOOL isConnected {搞定;组; }

公共Form1中()
{
的InitializeComponent();
isConnected = FALSE;
}

私人无效的LogMessage(字符串消息,诠释类)
{
如果(类== 1)
{
ListViewItem的项目=新的ListViewItem(消息);
item.BackColor = Color.LightGreen;
item.UseItemStyleForSubItems = TRUE;
Log.Items.Add(项目).SubItems.Add(DateTime.Now.ToString());
}
如果(类别== 2)
{
ListViewItem的项目=新的ListViewItem(消息);
item.BackColor = Color.Orange;
item.UseItemStyleForSubItems = TRUE;
Log.Items.Add(项目).SubItems.Add(DateTime.Now.ToString());
}
如果(类别== 3)
{
ListViewItem的项目=新的ListViewItem(消息);
item.BackColor = Color.Yellow;
item.UseItemStyleForSubItems = TRUE;
Log.Items.Add(项目).SubItems.Add(DateTime.Now.ToString());
}
如果(类别== 0)
{
Log.Items.Add(消息).SubItems.Add(DateTime.Now.ToString());
}
}

私人无效连接()
{
的LogMessage(发现并接受主服务器的连接。等待回复... 1);
Status.Text =接!;
Status.ForeColor = Color.Green;

commandsThread =新主题(新的ThreadStart(RecieveCommands));

sendClientInfo();
}

私人无效exitButton_Click(对象发件人,EventArgs五)
{
断开();
exitButton.Enabled = FALSE;
exitButton.Text =关闭...;

如果(connectionThread!= NULL)
{
,而(connectionThread.IsAlive)
{
Application.DoEvents();
}
}

this.Close();
}

私人无效Form1_Load的(对象发件人,EventArgs五)
{
连接();
}

私人无效断开()
{
RequestExitConnectionThread = TRUE;

如果(masterServer!= NULL)
masterServer.Close();

如果(connectionThread!= NULL)
connectionThread.Abort();

的LogMessage(关闭Client请等待程序的线程结束。,2);
}

私人无效断开()
{
Status.Text =断开连接;
Status.ForeColor = Color.Red;
连接();
}

私人无效连接()
{
的LogMessage(尝试连接到主服务器......,1);

connectionThread =新主题(新的ThreadStart(创建连接));
connectionThread.Start();
}

私人无效的CreateConnection()
{
INT I = 1;
BOOL成功= FALSE;

,而(!成功)
{

{
使用(masterServer =新的TcpClient())
{
IAsyncResult的结果= masterServer.BeginConnect(SERVERIP,MyPort上,NULL,NULL);
成功= result.AsyncWaitHandle.WaitOne(1000,FALSE);
}

如果(成功)
{
的BeginInvoke(新ConnectedDelegate(this.Connected),新的对象[] {});
中断;
}
,否则
{
Thread.sleep代码(2000);
的BeginInvoke(新AddMessageDelegate(的LogMessage),新的对象[] {连接重试#+ i.ToString()+主服务器还没有开始呢。,3});
}
}

{
MessageBox.Show(错误!);
}
I ++;
}

}

私人无效RecieveCommands()
{
MessageBox.Show(你好!);
commandReader =新的StreamReader(masterServer.GetStream());

串CommandResponse = commandReader.ReadLine();
字符串命令= NULL;

如果(CommandResponse!= NULL)
MessageBox.Show(收到命令,这不是空!);

如果(CommandResponse!= NULL)
{
MessageBox.Show(:收到空响应!);
的BeginInvoke(新AddMessageDelegate(的LogMessage),新的对象[] {断开连接从主服务器理由:收到空响应,1});
断开();
}
,否则如果(CommandResponse.StartsWith(0))
{
MessageBox.Show(收到0作为响应!);
命令= CommandResponse.Substring(2).Trim();

isConnected = FALSE;
的BeginInvoke(新AddMessageDelegate(的LogMessage),新的对象[] {断开连接从主服务器原因:+命令,1});
}
,否则如果(CommandResponse.StartsWith(1))
{
MessageBox.Show(收到1作为响应!);
isConnected = TRUE;
的BeginInvoke(新AddMessageDelegate(的LogMessage),新的对象[] {连接到主服务器成功。,1});
}
}


// ***********响应BELOW在这里************************* \\

私人无效sendClientInfo()
{
responseWriter =新的StreamWriter(masterServer.GetStream());

responseWriter.WriteLine(myIp.ToString());
responseWriter.Flush();
}

}
}


解决方案

您连接过程中添加一个检查,取消它,如果该程序退出应该有所帮助。



尝试创建连接()你的而(!成功)环内,但在你的尝试

 如果(RequestExitConnectionThread)
{
中断;
}

下面是一个异步BeginConnect()调用的一个例子:

  myTcpClient.BeginConnect(localhost的,80的onConnect,NULL); 



的onConnect功能:

 公共静态无效的onConnect(IAsyncResult的AR)
{
//做你的工作
}


This is one of my first issues. Whenever I exit out the program, tcpClient.Connect() takes forever to close. I've tried a ton of things, and none of them seem to work.

Take a look at the CreateConnection() thread, if the client isn't connected yet... and I close the program, it takes forever to close. If it IS connected, it closes immediately. I know this can be done with some kind of timeout trick, but i've tried a few and none of them worked.

Please provide a code example if you can.

Also, is there any good tutorial out there for C# on reading/writing the actual bytes with a buffer instead of this version that just does masterServer.writeLine() and masterServer.readline() or are they both just as efficient?

If you see anything else to help me improve this... by all means, go ahead. I'm trying to teach myself how to do this and I have no help, so don't let me go on doing something wrong if you see it!!! Thanks guys!

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;

namespace RemoteClient
{
    public partial class Form1 : Form
    {
        private int MyPort = 56789;
        private IPAddress myIp = IPAddress.Parse("210.232.115.79");
        private IPAddress serverIp = IPAddress.Parse("72.216.18.77"); // Master Server's IP Address
        public static TcpClient masterServer = new TcpClient();

        private StreamWriter responseWriter;
        private StreamReader commandReader;

        private Thread connectionThread;
        private Thread commandsThread;

        private bool RequestExitConnectionThread { get; set; }

        private delegate void AddMessageDelegate(string message, int category);
        private delegate void ConnectedDelegate();

        private bool isConnected { get; set; }

        public Form1()
        {
            InitializeComponent();
            isConnected = false;
        }

        private void LogMessage(string message, int category)
        {
            if (category == 1)
            {
                ListViewItem item = new ListViewItem(message);
                item.BackColor = Color.LightGreen;
                item.UseItemStyleForSubItems = true;
                Log.Items.Add(item).SubItems.Add(DateTime.Now.ToString());
            }
            if (category == 2)
            {
                ListViewItem item = new ListViewItem(message);
                item.BackColor = Color.Orange;
                item.UseItemStyleForSubItems = true;
                Log.Items.Add(item).SubItems.Add(DateTime.Now.ToString());
            }
            if (category == 3)
            {
                ListViewItem item = new ListViewItem(message);
                item.BackColor = Color.Yellow;
                item.UseItemStyleForSubItems = true;
                Log.Items.Add(item).SubItems.Add(DateTime.Now.ToString());
            }
            if (category == 0)
            {
                Log.Items.Add(message).SubItems.Add(DateTime.Now.ToString());
            }
        }

        private void Connected()
        {
            LogMessage("Found and Accepted Master Server's connection. Waiting for reply...",1);
            Status.Text = "Connected!";
            Status.ForeColor = Color.Green;

            commandsThread = new Thread(new ThreadStart(RecieveCommands));

            sendClientInfo();
        }

        private void exitButton_Click(object sender, EventArgs e)
        {
            Disconnect();
            exitButton.Enabled = false;
            exitButton.Text = "Closing...";

            if (connectionThread != null)
            {
                while (connectionThread.IsAlive)
                {
                    Application.DoEvents();
                }
            }

            this.Close();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Connect();
        }

        private void Disconnect()
        {
            RequestExitConnectionThread = true;

            if (masterServer != null)
                masterServer.Close();

            if (connectionThread != null)
                connectionThread.Abort();

            LogMessage("Closing Client. Please wait while Program threads end.", 2);
        }

        private void Disconnected()
        {
            Status.Text = "Disconnected";
            Status.ForeColor = Color.Red;
            Connect();
        }

        private void Connect()
        {
            LogMessage("Attempting to connect to Master Server...", 1);

            connectionThread = new Thread(new ThreadStart(CreateConnection));
            connectionThread.Start();
        }

        private void CreateConnection()
        {
            int i = 1;
            bool success = false;

            while (!success)
            {
                try
                {
                    using (masterServer = new TcpClient())
                    {
                        IAsyncResult result = masterServer.BeginConnect(serverIp, MyPort, null, null);
                        success = result.AsyncWaitHandle.WaitOne(1000, false);
                    }

                    if (success)
                    {
                        BeginInvoke(new ConnectedDelegate(this.Connected), new object[] {});
                        break;
                    }
                    else
                    {
                        Thread.Sleep(2000);
                        BeginInvoke(new AddMessageDelegate(LogMessage), new object[] { "Connection Retry # " + i.ToString() + ". Master Server hasn't been started yet.", 3 });
                    }
                }
                catch
                {
                    MessageBox.Show("Error!");
                }
                i++;
            }

        }

        private void RecieveCommands()
        {
            MessageBox.Show("Hello!");
            commandReader = new StreamReader(masterServer.GetStream());

            string CommandResponse = commandReader.ReadLine();
            string Command = null;

            if (CommandResponse != null)
                MessageBox.Show("Recieved Command that was NOT null!");

            if (CommandResponse != null)
            {
                MessageBox.Show("Recieved null response!");
                BeginInvoke(new AddMessageDelegate(LogMessage), new object[] { "Disconnected From Master Server. Reason: Recieved Null response.", 1 });
                Disconnected();
            }
            else if (CommandResponse.StartsWith("0"))
            {
                MessageBox.Show("Recieved 0 as a response!");
                Command = CommandResponse.Substring(2).Trim();

                isConnected = false;
                BeginInvoke(new AddMessageDelegate(LogMessage), new object[] { "Disconnected From Master Server. Reason: " + Command, 1 });
            }
            else if (CommandResponse.StartsWith("1"))
            {
                MessageBox.Show("Recieved 1 as a response!");
                isConnected = true;
                BeginInvoke(new AddMessageDelegate(LogMessage), new object[] { "Connected to Master Server Successfully.", 1 });
            }
        }


        //************************** RESPONSE'S BELOW HERE ************************* \\

        private void sendClientInfo()
        {
            responseWriter = new StreamWriter(masterServer.GetStream());

            responseWriter.WriteLine(myIp.ToString());
            responseWriter.Flush();
        }

    }
}

解决方案

Adding a check within your connection process to cancel it if the program is exiting should help.

Try adding this in CreateConnection() inside your while(!success) loop but before your try block:

if(RequestExitConnectionThread)
{
    break;
}

Here's an example of an asynchronous BeginConnect() call:

myTcpClient.BeginConnect("localhost", 80, OnConnect, null);

OnConnect function:

public static void OnConnect(IAsyncResult ar)
{
    // do your work
}

这篇关于C#我如何停止tcpClient.Connect()方法时,我已经准备好了节目结束?它只是坐在那里像10秒!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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