C#使用UDP接收消息时出现异常

时间:2015-06-12 13:29:41

标签: c# udp ip system.net.sockets

今天我在学校时制作了这段代码:

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

因为在学校我们使用.NET 4.0,所以我无法使用Async方法。当我回到家时,我修改它以使用.NET 4.6中的异步方法。但是现在当我尝试运行时抛出异常:

' System.Reflection.TargetInvocationException'在mscorlib.dll中 通过反射调用的方法引发的异常。其中在Public Form1()中写入了receiveMessage()

我该如何解决这个问题?

0 个答案:

没有答案