1
votes

This is my code for a simple chat program that works client to client. The problem is that when i click the send button an error is thrown.

The error is...

System.Net.Sockets.SocketException (0x80004005): An existing connection was forcibly closed by the remote host at System.Net.Sockets.SocketEndRecieveFrom(IAsyncResult asyncResult, EndPoint& endPoint) at ChatClientV1.MainForm.MessageCallBack(IAsynResult aResult)...line 36 below which is ...

int size = sck.EndReceiveFrom(aResult, ref epRemote);

    public MainForm()
    {
        InitializeComponent();

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

        //localIP = GetLocalIP();
        //friendIP = GetLocalIP();
        localIP = "192.168.0.17";
        friendIP = "192.168.0.17";
        friendPortNumber = "81";
        localPortNumber = "80";
        username = "Shawn";
    }

    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 epRemote);

            if (size > 0)
            {
                byte[] recieveData = new byte[1464];

                recieveData = (byte[])aResult.AsyncState;

                ASCIIEncoding eEncoding = new ASCIIEncoding();
                string recieveMessage = eEncoding.GetString(recieveData);

                messageListBox.Items.Add(username+": "+recieveMessage);
            }

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

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

    private void currentSettingsToolStripMenuItem_Click(object sender, EventArgs e)
    {
        CurrentSettingsFrom aCurrentSettingsForm = new CurrentSettingsFrom();
        aCurrentSettingsForm.ShowDialog();
    }

    private void sendFileToolStripMenuItem_Click(object sender, EventArgs e)
    {
        SendFileForm aSendFileForm = new SendFileForm();
        aSendFileForm.ShowDialog();
    }

    private void exitToolStripMenuItem_Click(object sender, EventArgs e)
    {
        this.Close();
    }

    private void appearanceToolStripMenuItem_Click(object sender, EventArgs e)
    {
        AppearanceForm aAppearanceFrom = new AppearanceForm();
        aAppearanceFrom.ShowDialog();
    }

    private void connectButton_Click(object sender, EventArgs e)
    {
        try
        {
            eplocal = new IPEndPoint(IPAddress.Parse(localIP), Convert.ToInt32(localPortNumber));
            sck.Bind(eplocal);

            epRemote = new IPEndPoint(IPAddress.Parse(friendIP), Convert.ToInt32(friendPortNumber));
            sck.Connect(epRemote);

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

            connectButton.Text = "Connected";
            connectButton.Enabled = false;
            sendMessageButton.Enabled = true;
            messageEntryField.Focus();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }

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

            sck.Send(msg);
            messageListBox.Items.Add(username + ": " + messageEntryField.Text);
            messageEntryField.Clear();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }
}

}

2

2 Answers

2
votes
host = Dns.GetHostEntry(Dns.GetHostName());

Due to this statement in the process of getting client ip, you are getting exception.

replace the code with

protected string GetClientIP()
{
    string result = string.Empty;
    string ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
    if (!string.IsNullOrEmpty(ip))
    {
        string[] ipRange = ip.Split(',');
        int le = ipRange.Length - 1;
        result = ipRange[0];
    }
    else
    {
        result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
    }

    return result;
}

now you will not get that error.

1
votes

You turned off the server in order listen request from clients. So try to turn on it if you have one or try to create a server in difference project and run it.

You can have an example here