已回答 UDP客户端错误

不详072

成员
已加入
2020年9月14日
留言内容
5
编程经验
Beginner
大家好,

我相信我有一个愚蠢的问题。
基本上我有三种形式;登录表单,主表单和自定义消息框

从今天开始就添加了登录表单,因此主表单和自定义消息框已经调试并且可以使用。
由于添加了登录表单,因此我收到一条错误消息:System.Net.Sockets.SocketException:“通常仅允许每个套接字地址(协议/网络地址/端口)使用一种”

所以我确实相信这个错误与我试图一次打开主窗体有关...

这是我登录后用来打开主窗体的代码。
当前在调试时,按Enter键后程序崩溃,然后显示错误。

该错误仅在我开始调试后出现,如果我停止调试,错误消失。


C#:
        private void enter_click(object sender, EventArgs e)
        {
            String pinCode = "1821";         // enter desired passcode here -- later addon: create a custom pin

            int.Parse(Passcode.Text);
            if (Passcode.Text == pinCode)
            {
            this.Visible = false;
            SPACE_CONTROL mainView = new SPACE_CONTROL();
            mainView.ShowDialog();
            this.Close();
        }
            else
            {
                Passcode.Text = "";
            }
        }

有谁知道如何解决这个问题?
 

跳伞

工作人员
已加入
2019年4月6日
留言内容
2,538
地点
弗吉尼亚州切萨皮克
编程经验
10+
Since you didn't show us how you open the port and more importantly close the port. Is it only opened and closed in your SPACE_CONTROL class? Is it opened and closed elsewhere? We can only guess. Chances are that you are not closing the port at all.
 

不详072

成员
已加入
2020年9月14日
留言内容
5
编程经验
Beginner
Since you didn't show us how you open the port and more importantly close the port. Is it only opened and closed in your SPACE_CONTROL class? Is it opened and closed elsewhere? We can only guess. Chances are that you are not closing the port at all.

抱歉,您是正确的。 UDP仅在SPACE_CONTROL中使用
您再次正确,因为我打开了一次。如下面的代码。

但是我该怎么做呢?


C#:
namespace ToolTest
{

    public partial class SPACE_CONTROL : Form
    {
        System.Windows.Forms.Timer t = new System.Windows.Forms.Timer();
        string data = "";
        bool ipSet = false;
        bool portSet = false;
        bool tableSet = false;

        UdpClient Client = new UdpClient(9101);
 

跳伞

工作人员
已加入
2019年4月6日
留言内容
2,538
地点
弗吉尼亚州切萨皮克
编程经验
10+
Since you are binding to the port at the time the class is constructed, you'll need to close the port on the Close event for the form. So you'll add an event handler for the Close event, and then call Close on the port:
 

羊皮

退休程序员
工作人员
已加入
2018年9月5日
留言内容
1,933
地点
英国
编程经验
10+
请显示您的代码,请在您使用此客户端的位置
 

不详072

成员
已加入
2020年9月14日
留言内容
5
编程经验
Beginner
请显示您的代码,请在您使用此客户端的位置

C#:
using System;
using System.Drawing;
using System.Net;
using System.Net.Configuration;
using System.Net.Sockets;
using System.Reflection;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Windows.Forms;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Net.NetworkInformation;
#pragma warning disable CS0105 // Using directive appeared previously in this namespace
using System.Windows.Forms;
#pragma warning restore CS0105 // Using directive appeared previously in this namespace
using System.Runtime.CompilerServices;



namespace ToolTest
{

    public partial class SPACE_CONTROL : Form
    {
        System.Windows.Forms.Timer t = new System.Windows.Forms.Timer();
        string data = "";
        bool ipSet = false;
        bool portSet = false;
        bool tableSet = false;

        UdpClient Client = new UdpClient(9101);
        
        public SPACE_CONTROL()
        {

            InitializeComponent();

            Confirm.Visible = false;


            IPAddress[] localIP = Dns.GetHostAddresses(Dns.GetHostName());
            foreach (IPAddress address in localIP)
            {
                if (address.AddressFamily == AddressFamily.InterNetwork)
                    TextBoxLocalIP.Text = address.ToString();
            }


            try
            {
                Client.BeginReceive(new AsyncCallback(recv), null);
            }
            catch (Exception ex)
            {
                RichTextBoxToReceive.Text += ex.Message.ToString();
            }

        }
        void recv(IAsyncResult res)
        {

            IPEndPoint RemoteIp = new IPEndPoint(IPAddress.Any, 1821);
            byte[] received = Client.EndReceive(res, ref RemoteIp);
            data = Encoding.UTF8.GetString(received);

            this.Invoke(new MethodInvoker(delegate
            {
                LogControl.Write(data);
                RichTextBoxToReceive.Text += "\n" + DateTime.Now.ToString("HH:mm:ss") + ": " + data;
            }));

            Client.BeginReceive(new AsyncCallback(recv), null);

        }

        private void button_click(object sender, EventArgs e)
        {
            if (TextBoxTable.Text == "0")
            {
                TextBoxTable.Clear();
            }
            Button button = (Button)sender;
            TextBoxTable.Text = TextBoxTable.Text + button.Text;

            if (TextBoxTable.TextLength > 3)
            {
                TextBoxTable.Text = "0";
                this.Alert("Oops. I think that's not possible! \nStart over! ");
            }
        }


        private void buttonC_click(object sender, EventArgs e)
        {
            TextBoxTable.Text = "0";
        }

        private void enter_click(object sender, EventArgs e)
        {
            int tableValue = int.Parse(TextBoxTable.Text);
            if (tableValue > 100 && tableValue <= 300)
            {
                TextBoxActiveTable.Text = TextBoxTable.Text;
                LogControl.Write("Table number " + tableValue + " is set.");
                TextBoxTable.Text = "0";
                tableSet = true;
                TextBoxActiveTable.BackColor = Color.DarkGreen;
                TextBoxActiveTable.ForeColor = Color.Red;

            }
            else
            {
                TextBoxTable.Text = "0";
                tableSet = false;
                this.Alert("Oops. that number is not possible!  \nStart over! ");
            }
        }

        private void ButtonApply_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(TextBoxPort.Text))
            {
                portSet = false;
            }
            else
            {
                portSet = true;
            }

            IPAddress ipAddr;
            string addr = TextBoxIP.Text;

            bool res = IPAddress.TryParse(addr, out ipAddr);
            if (res)
            {
                ipSet = true;
            }
            else
            {
                ipSet = false;
            }

            if (ipSet == true && portSet == true)
            {
                TextBoxActiveIP.Text = TextBoxIP.Text;
                TextBoxActivePort.Text = TextBoxPort.Text;
                TextBoxActiveIP.BackColor = Color.DarkGreen;
                TextBoxActivePort.BackColor = Color.DarkGreen;
                TextBoxActiveIP.ForeColor = Color.Red;
                TextBoxActivePort.ForeColor = Color.Red;
                LogControl.Write("IP address is set manual to: " + TextBoxActiveIP.Text + ", Port number is set manual to: " + TextBoxActivePort.Text);

            }
            else if (ipSet == true && !TextBoxPort.Equals(null))
            {
                this.Alert("Don't forget to set the UDP port...");
            }
            else if (ipSet == false && !TextBoxPort.Equals(null))
                this.Alert("We are missing some credentials here... ");
        }

        private async void UDPsend(object sender, EventArgs e)
        {
            if (ipSet == false)
            {
                this.Alert("You did not insert any credentials to send to..!");
                RichTextBoxToSend.Clear();
            }
            else if (portSet == false)
            {
                this.Alert("You did not insert any credentials to send to..!");
                RichTextBoxToSend.Clear();
            }
            else if (RichTextBoxToSend.TextLength == 0)
            {
                this.Alert("You did not inserted any data to send..!");
                RichTextBoxToSend.Clear();
            }
            else
            {


                byte[] packetData = System.Text.ASCIIEncoding.ASCII.GetBytes(RichTextBoxToSend.Text);  //("string")

                string IP = TextBoxActiveIP.Text; //"10.168.1.106"
                int port = int.Parse(TextBoxActivePort.Text); //2000

                IPEndPoint ep = new IPEndPoint(IPAddress.Parse(IP), port);

                Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                client.SendTo(packetData, ep);
                LogControl.Write("Message sent to: " + TextBoxActiveIP.Text + ":" + TextBoxActivePort.Text);
                LogControl.Write("message: " + RichTextBoxToSend.Text);
                RichTextBoxToSend.Clear();
                Confirm.Visible = true;
                await Task.Delay(500);
                Confirm.Visible = false;
            }
        }

        private void RichTextBoxToReceive_TextChanged(object sender, EventArgs e)
        {
            RichTextBoxToReceive.SelectionStart = RichTextBoxToReceive.Text.Length;
            RichTextBoxToReceive.ScrollToCaret();  //--autoscroll function
        }

        private void ClearReceivedButton(object sender, EventArgs e)
        {
            RichTextBoxToReceive.Clear();
        }

        private async void availableButton(object sender, EventArgs e)
        {
            if (tableSet == true && ipSet == true && portSet == true)
            {
                byte[] packetData = System.Text.ASCIIEncoding.ASCII.GetBytes(TextBoxActiveTable.Text + "_available");  //("string")

                string IP = TextBoxActiveIP.Text; //"10.168.1.106"
                int port = int.Parse(TextBoxActivePort.Text); //2000

                IPEndPoint ep = new IPEndPoint(IPAddress.Parse(IP), port);

                Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                client.SendTo(packetData, ep);

                Confirm.Visible = true;
                await Task.Delay(500);
                Confirm.Visible = false;

                Available.BackColor = Color.LimeGreen;
                Available.ForeColor = Color.Black;

                Idle.BackColor = Color.Black;
                Idle.ForeColor = Color.LimeGreen;

                Ordered.BackColor = Color.Black;
                Ordered.ForeColor = Color.LimeGreen;

                Off.BackColor = Color.Black;
                Off.ForeColor = Color.LimeGreen;

                Ping.BackColor = Color.Black;
                Ping.ForeColor = Color.LimeGreen;
            }
            else if (tableSet == false && ipSet == true && portSet == true)
            {
                this.Alert("First you need to set a table number, please");
            }
            else
            {
                this.Alert("You did not insert any credentials to send to..!");
            }
        }

        private async void idleButton(object sender, EventArgs e)
        {
            if (tableSet == true && ipSet == true && portSet == true)
            {
                byte[] packetData = System.Text.ASCIIEncoding.ASCII.GetBytes(TextBoxActiveTable.Text + "_idle");  //"string"

                string IP = TextBoxActiveIP.Text; //"10.168.1.106"
                int port = int.Parse(TextBoxActivePort.Text); //2000

                IPEndPoint ep = new IPEndPoint(IPAddress.Parse(IP), port);

                Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                client.SendTo(packetData, ep);

                Confirm.Visible = true;
                await Task.Delay(500);
                Confirm.Visible = false;

                Available.BackColor = Color.Black;
                Available.ForeColor = Color.LimeGreen;

                Idle.BackColor = Color.LimeGreen;
                Idle.ForeColor = Color.Black;

                Ordered.BackColor = Color.Black;
                Ordered.ForeColor = Color.LimeGreen;

                Off.BackColor = Color.Black;
                Off.ForeColor = Color.LimeGreen;

                Ping.BackColor = Color.Black;
                Ping.ForeColor = Color.LimeGreen;
            }
            else if (tableSet == false && ipSet == true && portSet == true)
            {
                this.Alert("First you need to set a table number, please");
            }
            else
            {
                this.Alert("You did not insert any credentials to send to..!");
            }
        }

        private async void orderedButton(object sender, EventArgs e)
        {
            if (tableSet == true && ipSet == true && portSet == true)
            {
                byte[] packetData = System.Text.ASCIIEncoding.ASCII.GetBytes(TextBoxActiveTable.Text + "_ordered");  //"string"

                string IP = TextBoxActiveIP.Text; //"10.168.1.106"
                int port = int.Parse(TextBoxActivePort.Text); //2000

                IPEndPoint ep = new IPEndPoint(IPAddress.Parse(IP), port);

                Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                client.SendTo(packetData, ep);

                Confirm.Visible = true;
                await Task.Delay(500);
                Confirm.Visible = false;

                Available.BackColor = Color.Black;
                Available.ForeColor = Color.LimeGreen;

                Idle.BackColor = Color.Black;
                Idle.ForeColor = Color.LimeGreen;

                Ordered.BackColor = Color.LimeGreen;
                Ordered.ForeColor = Color.Black;

                Off.BackColor = Color.Black;
                Off.ForeColor = Color.LimeGreen;

                Ping.BackColor = Color.Black;
                Ping.ForeColor = Color.LimeGreen;
            }
            else if (tableSet == false && ipSet == true && portSet == true)
            {
                this.Alert("First you need to set a table number, please");
            }
            else
            {
                this.Alert("You did not insert any credentials to send to..!");
            }
        }

        private async void offButton(object sender, EventArgs e)
        {
            if (tableSet == true && ipSet == true && portSet == true)
            {
                byte[] packetData = System.Text.ASCIIEncoding.ASCII.GetBytes(TextBoxActiveTable.Text + "_off");  //"string"

                string IP = TextBoxActiveIP.Text; //"10.168.1.106"
                int port = int.Parse(TextBoxActivePort.Text); //2000

                IPEndPoint ep = new IPEndPoint(IPAddress.Parse(IP), port);

                Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                client.SendTo(packetData, ep);

                Confirm.Visible = true;
                await Task.Delay(500);
                Confirm.Visible = false;

                Available.BackColor = Color.Black;
                Available.ForeColor = Color.LimeGreen;

                Idle.BackColor = Color.Black;
                Idle.ForeColor = Color.LimeGreen;

                Ordered.BackColor = Color.Black;
                Ordered.ForeColor = Color.LimeGreen;

                Off.BackColor = Color.LimeGreen;
                Off.ForeColor = Color.Black;

                Ping.BackColor = Color.Black;
                Ping.ForeColor = Color.LimeGreen;
            }
            else if (tableSet == false && ipSet == true && portSet == true)
            {
                this.Alert("First you need to set a table number, please");
            }
            else
            {
                this.Alert("You did not insert any credentials to send to..!");
            }
        }

        private async void pingButton(object sender, EventArgs e)
        {
            if (tableSet == true && ipSet == true && portSet == true)
            {
                byte[] packetData = System.Text.ASCIIEncoding.ASCII.GetBytes(TextBoxActiveTable.Text + "_ping");  //test: "string"

                string IP = TextBoxActiveIP.Text; //"10.168.1.106"
                int port = int.Parse(TextBoxActivePort.Text); //2000

                IPEndPoint ep = new IPEndPoint(IPAddress.Parse(IP), port);

                Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                client.SendTo(packetData, ep);

                Confirm.Visible = true;
                await Task.Delay(500);
                Confirm.Visible = false;

                Available.BackColor = Color.Black;
                Available.ForeColor = Color.LimeGreen;

                Idle.BackColor = Color.Black;
                Idle.ForeColor = Color.LimeGreen;

                Ordered.BackColor = Color.Black;
                Ordered.ForeColor = Color.LimeGreen;

                Off.BackColor = Color.Black;
                Off.ForeColor = Color.LimeGreen;

                Ping.BackColor = Color.LimeGreen;
                Ping.ForeColor = Color.Black;
            }
            else if (tableSet == false && ipSet == true && portSet == true)
            {
                this.Alert("First you need to set a table number, please");
            }
            else
            {
                this.Alert("You did not insert any credentials to send to..!");
            }
        }

        private void noneButton(object sender, EventArgs e)
        {
            Available.BackColor = Color.Black;
            Available.ForeColor = Color.LimeGreen;

            Idle.BackColor = Color.Black;
            Idle.ForeColor = Color.LimeGreen;

            Ordered.BackColor = Color.Black;
            Ordered.ForeColor = Color.LimeGreen;

            Off.BackColor = Color.Black;
            Off.ForeColor = Color.LimeGreen;

            Ping.BackColor = Color.Black;
            Ping.ForeColor = Color.LimeGreen;
        }
        private void resetClick(object sender, EventArgs e)
        {
            tableSet = false;
            ipSet = false;
            portSet = false;

            TextBoxTable.Text = "0";
            TextBoxActiveIP.Clear();
            TextBoxActiveTable.Clear();
            TextBoxActivePort.Clear();
            RichTextBoxToReceive.Clear();
            RichTextBoxToSend.Clear();
            TextBoxIP.Clear();
            TextBoxPort.Clear();
            TextBoxPort.Text = "";
            TextBoxActiveIP.BackColor = Color.Black;
            TextBoxActivePort.BackColor = Color.Black;
            TextBoxActiveTable.BackColor = Color.Black;
            Available.BackColor = Color.Black;
            Available.ForeColor = Color.LimeGreen;
            Idle.BackColor = Color.Black;
            Idle.ForeColor = Color.LimeGreen;
            Ordered.BackColor = Color.Black;
            Ordered.ForeColor = Color.LimeGreen;
            Off.BackColor = Color.Black;
            Off.ForeColor = Color.LimeGreen;
            Ping.BackColor = Color.Black;
            Ping.ForeColor = Color.LimeGreen;
        }

        private async void enterPressed(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)

            {
                if (ipSet == false)
                {
                    this.Alert("You did not insert any credentials to send to..!");
                    RichTextBoxToSend.Clear();
                    e.SuppressKeyPress = true;
                }
                else if (portSet == false)
                {
                    this.Alert("You did not insert any credentials to send to..!");
                    RichTextBoxToSend.Clear();
                    e.SuppressKeyPress = true;
                }
                else if (RichTextBoxToSend.TextLength == 0)
                {
                    this.Alert("You did not inserted any data to send..!");
                    RichTextBoxToSend.Clear();
                    e.SuppressKeyPress = true;
                }
                else
                {
                    byte[] packetData = System.Text.ASCIIEncoding.ASCII.GetBytes(RichTextBoxToSend.Text);  //"string"

                    string IP = TextBoxActiveIP.Text; //"10.168.1.106"
                    int port = int.Parse(TextBoxActivePort.Text); //2000

                    IPEndPoint ep = new IPEndPoint(IPAddress.Parse(IP), port);

                    Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                    client.SendTo(packetData, ep);
                    e.SuppressKeyPress = true;

                    RichTextBoxToSend.Clear();

                    Confirm.Visible = true;
                    await Task.Delay(500);
                    Confirm.Visible = false;

                }
            }
        }

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (keyData == (Keys.Q | Keys.Control))
            {
                Close();
                return true;
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }

        private void SPACE_CONTROL_Load(object sender, EventArgs e)
        {

            this.Visible = false;
            LogOn loginView = new LogOn();
            loginView.ShowDialog();
            this.Close();
      

            t.Interval = 1000;

            t.Tick += new EventHandler(this.t_Tick);
 

            t.Start();

        }


        //Timer event handler
        private void t_Tick(object sender, EventArgs e)
        {
            //get current time
            int hh = DateTime.Now.Hour;
            int mm = DateTime.Now.Minute;
            int ss = DateTime.Now.Second;

            string time = "";

            if (hh < 10)
            {
                time += "0" + hh;
            }
            else
            {
                time += hh;
            }
            time += ":";

            if (mm < 10)
            {
                time += "0" + mm;
            }
            else
            {
                time += mm;
            }
            time += ":";

            if (ss < 10)
            {
                time += "0" + ss;
            }
            else
            {
                time += ss;
            }

            Clock.Text = time;

        }
        public void Alert(string msg)
        {
            msg frm = new msg();
            frm.showAlert(msg);
        }

        public class LogControl
        {
            private static string _Path = string.Empty;
            private static bool DEBUG = true;

            public static void Write(string msg)
            {
                _Path = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
                try
                {
                    using (StreamWriter w = File.AppendText(Path.Combine(_Path, "log.txt")))
                    {
                        Log(msg, w);
                    }
                    if (DEBUG)
                        Console.WriteLine(msg);
                }
                catch (Exception)
                {
                    //Handle
                }
            }

            static private void Log(string msg, TextWriter w)
            {
                try
                {
                    w.Write(Environment.NewLine);
                    w.Write("[{0} {1}]", DateTime.Now.ToLongTimeString(), DateTime.Now.ToLongDateString());
                    w.Write("\t");
                    w.WriteLine(" {0}", msg);
                    w.WriteLine("-----------------------");
                }
                catch (Exception)
                {
                    //Handle
                }
            }
        }

        private void logOff_Click(object sender, EventArgs e)
        {
            this.Visible = false;
            LogOn loginView = new LogOn();
            loginView.ShowDialog();
            this.Close();
        }
    }
}
 

跳伞

工作人员
已加入
2019年4月6日
留言内容
2,538
地点
弗吉尼亚州切萨皮克
编程经验
10+
All you are doing in that code in post #7 is closing your SPACE_CONTROL form. You are not closing the port. Where are you closing the port?

Also you'll run into an interesting issue with your logoff_Click() handler. You are launching the LogOn form. According to post #1, you are launching SPACE_CONTROL form, and as noted, you try to open the port when the form is constructed.

我建议延迟打开端口...当您第一次需要该端口时将其打开,并保持打开状态,直到需要关闭表单为止。

This still won't completely fix your catch-22 with logoff_Click(). One way to fix the catch-22 for this case is to close the port before showing the log on form.
 

跳伞

工作人员
已加入
2019年4月6日
留言内容
2,538
地点
弗吉尼亚州切萨皮克
编程经验
10+
我已经尝试了一些方法,但是不确定如何执行此操作。每次我写UdpClient.Close();它导致错误
That's like like because you are trying to use an instance method like a static method. You should be writing Client.Close() so that you access the instance method. You'll obviously get errors if you were writing UdpClient.Close();.

学习如何编程的一部分是学习如何阅读文档。令您惊讶的是,您对所提供的当前代码没有什么帮助。我本来希望,如果您走到了那一步,您已经对语言有了足够的了解,可以了解如何初始化事物以及如何清理事物。
 
最佳 底部