Answered Udp client error

unknown072

Member
Joined
Sep 14, 2020
Messages
5
Programming Experience
Beginner
Hi all,

I have a stupid question I believe.
Basically I have three forms; Login form, Main form and Custom Message Box

The login form is added since today, so main form and custom message box are already debugged and functional.
Since the login form is added I receive a error message: System.Net.Sockets.SocketException: 'Only one usage of each socket address (protocol/network address/port) is normally permitted'

So I do believe this error has to do with that I'm trying to open the main form more as once ...

This is the code which I'm using to open the main form after log in.
Currently on debug the program crashes after I press enter and then shows me the error.

The error appears only after I've started debug, if I stop with debugging the error disappears.


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 = "";
            }
        }

Does anyone knows how to solve this?
 
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.
 
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.

Sorry, you are correct. the UDP is only used in SPACE_CONTROL
And you're correct once again, since I'm opening it once. As in the code below.

But how can I make this?


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);
 
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:
 
Show your code please where you are using this client

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();
        }
    }
}
 
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.

I recommend doing a lazy open of the port... Open the port when you first need it and leave it open until it's time to close the form.

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.
 
I've tried some things, but I'm not sure how to do this. Everytime I write the UdpClient.Close(); it results in error
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();.

Part of learning how to program is learning how to read the documentation. I'm surprised you got as far as you did with the current code you've presented. I would have expected that if you'd gotten that far, you'd already learned enough about the language to know about how things are initialized, and how they should be cleaned up.
 
Back
Top Bottom