-2

Why won't this code work? I'm new in C# and took this from a tutorial. No error in the code but it crashes in debug mode. Thanks!

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

namespace Chat1
{
    public partial class Form1 : Form
    {
        Socket sck;
        EndPoint epLocal, epRemote;
        byte[] buffer;
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //Set up socket
            sck = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

            sck.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);

            //Get User IP

            textLocalIp.Text = GetLocalIp();
            textRemoteIp.Text = GetLocalIp();
        }

        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 buttonConnect_Click(object sender, EventArgs e)
        {
            // Binding Socket
            epLocal = new IPEndPoint(IPAddress.Parse(textLocalIp.Text), Convert.ToInt32(textLocalPort.Text));
            sck.Bind(epLocal);
            // Connect to Remote IP

            epRemote = new IPEndPoint(IPAddress.Parse(textRemoteIp.Text), Convert.ToInt32(textRemotePort.Text));
            sck.Bind(epRemote); // This is were it directs me when crashing
            //Specific Port

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

        }

        private void MessageCallBack(IAsyncResult aResult)
        {
            try
            {
                byte[] recieveData = new byte[1500];
                recieveData = (byte[])aResult.AsyncState;
                //Convert Byte To String
                ASCIIEncoding aEncoding = new ASCIIEncoding();
                string receivedMessage = aEncoding.GetString(recieveData);

                //Adding this item into Textbox

                listMessage.Items.Add("Partner: " + receivedMessage);

                buffer = new byte[1500];
                sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buffer);
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void buttonSend_Click(object sender, EventArgs e)
        {
            // Convert String to Byte
            ASCIIEncoding aEncoding = new ASCIIEncoding();
            byte[] sendingMessage = new byte[1500];
            sendingMessage = aEncoding.GetBytes(textMessage.Text);

            // Sending the Enconded message
            sck.Send(sendingMessage);
            //Add to the Listbox
            listMessage.Items.Add("Me: " + textMessage.Text);
            textMessage.Text = "";
    }
}

}

Tharwen
  • 3,057
  • 2
  • 24
  • 36
simedr
  • 11
  • 4

1 Answers1

0

You're binding the same Socket to multiple endpoints (first epLocal, then epRemote). You need to make a new socket for epRemote.

For example:

Declare two Sockets at the top of the class:

Socket remoteSocket;
Socket localSocket;

Initialize them in Form1_Load:

remoteSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
localSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);

And in buttonConnect_Click, bind them to the separate IPEndPoints:

epLocal = new IPEndPoint(IPAddress.Parse(textLocalIp.Text), Convert.ToInt32(textLocalPort.Text));
localSocket.Bind(epLocal);

epRemote = new IPEndPoint(IPAddress.Parse(textRemoteIp.Text), Convert.ToInt32(textRemotePort.Text));
remoteSocket.Bind(epRemote);

Since it looks like you're trying to read from the remote IPEndPoint, you'll need to do it like this:

buffer = new byte[1500];
remoteSocket.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buffer);
Tharwen
  • 3,057
  • 2
  • 24
  • 36
  • I don't think this qualifies as an answer. – Marco Oct 13 '14 at 10:37
  • @Serv Why is it not an answer? – o_weisman Oct 13 '14 at 10:38
  • 1
    I would at least post the correct piece of code with the changes and 1 or 2 sentences of why these changes are neccessary. As it stands right now, this is just a comment. – Marco Oct 13 '14 at 10:40
  • As Serv said, I would need the changed code, I tried changing it using the little knowledge I've got, with no success – simedr Oct 13 '14 at 10:42
  • There you go. Lots of code. I have to go now so if anyone feels like it needs more please feel free to edit away. – Tharwen Oct 13 '14 at 10:49
  • It won't start :/ I'll try to look at it a bit more carefully when I get home :) But thank you anyway : – simedr Oct 13 '14 at 12:48
  • If anyone is still here, localSocket and sck is not defined and I don't know what to assign it to. Is that why it won't start? – simedr Oct 13 '14 at 14:25
  • I think Serv meant for you to change your sck to localSocket and just add remoteSocket – o_weisman Oct 14 '14 at 07:53
  • And remove epLocal and epRemote? – simedr Oct 14 '14 at 09:01
  • No, keep them both and bind localSocket to epLocal and remoteSocket to epRemote. It's really not clear what you want to do with this though, so there's not much we can help with. – Tharwen Oct 14 '14 at 12:19
  • Oh, sorry. What I want to do is to create a chatting program between two computers within the same network. And coonnect those two by typing in an IP and a Port :) – simedr Oct 14 '14 at 13:09
  • Do you even need a local port then? I actually don't know much about this sort of thing. I just saw why the error was happening in the first place. – Tharwen Oct 14 '14 at 15:56
  • I don't know much about it either, but I believe so. Anyway, thanks for the help :) – simedr Oct 14 '14 at 17:20