C# Exception in receiving message with UDP

178 Views Asked by At

today I made this code when I was at school:

using System;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Text;
using System.Text.RegularExpressions;

namespace Chat
{
 public partial class Form1 : Form
 {
    UdpClient udp = new UdpClient();
    string username;

    public Form1()
    {
        InitializeComponent();

        receiveMessage();
    }

    bool checkData()
    {
        Regex ipValid = new Regex(@"^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}$");

        if (!(ipValid.Match(txtAddress.Text).Success)) { label4.Text = "Wrong IP address!"; return false; }
        if (txtPort.Text == "") { label4.Text = "Your port is wrong!"; return false; }
        if(txtUsername.Text == "") { label4.Text = "Your username can't be Null!"; return false; }

        return true;
    }

    async void receiveMessage()
    {
        while (true)
        {
            var result = await udp.ReceiveAsync();
            string receivedString = convertToString(result.Buffer);
            txtChat.Text += String.Format(receivedString);
        }
    }
    void sendMessage(byte[] message)
    {
        udp.Send(message, message.Length);

        txtChat.Text += convertToString(message) + "\n";
    }
    void clearChat()
    {
        sendMessage(convertToBytes("[COMMAND]CLEAR"));
        txtChat.Clear();
    }

    void connectToServer()
    {
        label4.Text = "";

        if (checkData())
        {
            udp.Connect(txtAddress.Text, Convert.ToInt16(txtPort.Text));
            sendMessage(convertToBytes("[+]" + username + " joined the chat room!"));
            username = txtUsername.Text;
        }
    }

    byte[] convertToBytes(string message)
    {
        return Encoding.ASCII.GetBytes(message);
    }
    string convertToString(byte[] message)
    {
        return Encoding.ASCII.GetString(message);
    }

    private void button2_Click(object sender, EventArgs e)
    {
        clearChat();
        connectToServer();
    }
    private void button1_Click(object sender, EventArgs e)
    {
        sendMessage(convertToBytes("[" + username + "]: >>" + txtMessage.Text));
    }
    private void button3_Click(object sender, EventArgs e)
    {
        clearChat();
    }
}
}

Since at school we use .NET 4.0, I wasn't able to use Async method. When I returned home, I modified it to works with async method in .NET 4.6. But now when I try run it throw an exception:

'System.Reflection.TargetInvocationException' in mscorlib.dll The exception that is thrown by methods invoked through reflection. where there is written receiveMessage() in Public Form1()

How can I solve this?

0

There are 0 best solutions below