c# socket disconnect

Gast #4872815
Lesenswert?

Hi,

Ich möchte ein simples chatprogramm schreiben über das zwei clients 
kommunizieren. Ich kann verbindung mit einem Client aufbauen, senden und 
empfangen. Aber wenn ich die Verbidung trenne und mit einer anderen 
Portnummer eine neue Verbindung aufbauen möchte wird eine Exception 
ausgelöst. Exception befindet sich im Anhang! Kann mir jemand 
weiterhelfen? Verbindungstrennung soll in Funktion button3_Click(...) 
stattfinden.

[c]
 Socket sck;
        EndPoint epLocal, epRemot;

        public Form1()
        {
            InitializeComponent();
            sck = new Socket(AddressFamily.InterNetwork, 
SocketType.Dgram, ProtocolType.Udp);
            sck.SetSocketOption(SocketOptionLevel.Socket, 
SocketOptionName.ReuseAddress, true);

            textBoxIPClient1.Text = getLocalIp();
            textBoxIPClient2.Text = getLocalIp();

            button2.Enabled = false;

        }

        private string getLocalIp()
        {
            IPHostEntry host;
            host = Dns.GetHostEntry(Dns.GetHostName());

            foreach (IPAddress ip in host.AddressList)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    return ip.ToString();
                }
            }

            return "127.0.0.1";
        }

        private void MessageCallBack(IAsyncResult aResult)
        {
            try
            {
                int size = sck.EndReceiveFrom(aResult, ref epRemot);
                if (size > 0)
                {
                    byte[] receivedData = new byte[1464];
                    receivedData = (byte[])aResult.AsyncState;

                    ASCIIEncoding eEncoding = new ASCIIEncoding();
                    string receivedMessage = 
eEncoding.GetString(receivedData);
                    listBox1.Items.Add("Friend: " + receivedMessage);
                }
                byte[] buffer = new byte[1500];
                sck.BeginReceiveFrom(buffer, 0, buffer.Length, 
SocketFlags.None, ref epRemot, new AsyncCallback(MessageCallBack), 
buffer);
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {

            try
            {
                epLocal = new 
IPEndPoint(IPAddress.Parse(textBoxIPClient1.Text), 
Convert.ToInt32(textBoxPORTClient1.Text));
                sck.Bind(epLocal);

                epRemot = new 
IPEndPoint(IPAddress.Parse(textBoxIPClient2.Text), 
Convert.ToInt32(textBoxPORTClient2.Text));
                sck.Connect(epRemot);

                byte[] buffer = new byte[1500];
                sck.BeginReceiveFrom(buffer, 0, buffer.Length, 
SocketFlags.None, ref epRemot, new AsyncCallback(MessageCallBack), 
buffer);

                button1.Text = "Connected";
                // button1.Enabled = false;

                button2.Enabled = true;
                textBoxMessage.Focus();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            try {
                System.Text.ASCIIEncoding enc = new 
System.Text.ASCIIEncoding();
                byte[] msg = new byte[1500];
                msg = enc.GetBytes(textBoxMessage.Text);
                sck.Send(msg);

                listBox1.Items.Add("You: " + textBoxMessage.Text);
                textBoxMessage.Clear();

            }
            catch(Exception ex){
                MessageBox.Show(ex.ToString());
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                sck.Disconnect(true);
                sck.Close();

            }catch(Exception ex){
                MessageBox.Show(ex.ToString());
            }
        }

[\c]
Angehängte Dateien:
Gast #4873194
Lesenswert?

xtreme schrieb:
> wie mache ich aber disconnect? Ich möchte den alten Socket schließen und
> die Portnummer wieder freigeben.

so wie du es schon jetzt machst.

eventuell geht es schon so:

button3_Click
1
sck.Disconnect(true);
2
sck.Close();
3
sck = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
4
sck.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);

Antwort schreiben

Bitte melde dich an, um einen Beitrag zu schreiben.

oder

Mit Google-Account einloggen

Die Registrierung ist kostenlos und dauert nur eine Minute.

Jetzt registrieren