C#UDP Chat没有收到任何消息

时间:2014-08-12 08:01:43

标签: c# udp chat

我尝试用C#编写UDP-Chat。

我在聊天程序中有一些意想不到的行为,当我在连接到同一网络的两台不同机器上启动程序时。在第一个mashine,程序工作正常,它可以正确发送和回收消息,但在第二台机器上,它只能发送消息,但它不能回收它们。

我用第3个mashine(带有桥接网络接口的VM)测试了这个,但是结果相同,它只是可以发送消息而不接收。

我的代码中是否有错误或是设计错误?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Net.Sockets;
using System.Net;
using System.Diagnostics;
using System.Threading;
using System.Net.NetworkInformation;
using System.ComponentModel;
using System.Data;



namespace CScharpChat
{
/// <summary>
/// Interaktionslogik für Chat_window.xaml
/// </summary>
public partial class Chat_window : Window
{
    string name = "testuser";

    UdpClient receiveClient = new UdpClient(1800);
    IPEndPoint receiveEndPint = new IPEndPoint(IPAddress.Any, 0);

    public Chat_window(string name)
    {
        this.name = name;
        fileWriter("Chat started", false); // write the initial start date in the errorfile
        InitializeComponent();
        Message_Load();  // starts the listen server theread
    }

    private void Message_Load()
    {
        lb_chat.Items.Add(name + " Joined the room...");
        Thread rec = new Thread(ReceiveMessageFn);
        rec.Start();
    }

    private void ReceiveMessageFn()
    {
        try
        {
            while (true)
            {
                Byte[] receve = receiveClient.Receive(ref receiveEndPint);
                string message = Encoding.UTF8.GetString(receve);

                if (message == name + " logged out...")
                {
                    break;
                }
                else
                {
                    if (message.Contains(name + " says >>"))
                    {
                        message = message.Replace(name + " says >>", "Me says >>");
                    }

                    ShowMessage(message);
                }
            }

            //Thread.CurrentThread.Abort();
            //Application.Current.Shutdown();

        }
        catch (Exception e)
        {
            //errorHandler(e);
        }
    }

    private void ShowMessage(string message)
    {
        if (lb_chat.Dispatcher.CheckAccess())
        {
            lb_chat.Items.Add(message);// add Item to list-box
            lb_chat.ScrollIntoView(lb_chat.Items[lb_chat.Items.Count - 1]);// scroll down to current Item
            lb_chat.UpdateLayout();
        }
        else {
            lb_chat.Dispatcher.BeginInvoke(
                new Action<string>(ShowMessage), message); // if list-box is not access able get access
            return;
        }
    }

    private void tb_eingabe_GotFocus(object sender, RoutedEventArgs e)
    {
        tb_eingabe.Text = ""; 
    }
    private void btn_submit_Click(object sender, RoutedEventArgs e)
    {
        submit_message();
    }
    private void tb_eingabe_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Return)
        {
            submit_message();
        }
    }

    void submit_message()
    {
        if (tb_eingabe.Text != "")
        {

            string data = name + " says >> " + tb_eingabe.Text;
            SendMessage(data);

            tb_eingabe.Clear(); // clear the textbox-values
            tb_eingabe.Focus(); // get focus on tb if the submit button was used, the tb lost the focus
        }
    }

    private void SendMessage(string data)
    {
        try{
            UdpClient sendClient = new UdpClient();
            Byte[] message = Encoding.UTF8.GetBytes(data); // use UTF8 for international encoding
            IPEndPoint endPoint = new IPEndPoint(IPAddress.Broadcast, 1800); // use a broadcast with the given port
            sendClient.Send(message, message.Length, endPoint);
            sendClient.Close();
        }
        catch (Exception e)
        {
            errorHandler(e);
        }

    }

    private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
    {
        string data = name + " logged out..."; 
        SendMessage(data); // send a logout message to the other chat peers
    }

    // debugging functions
    static void errorHandler(Exception errorMsg)
    {
        MessageBox.Show(errorMsg.ToString()); // create a error-message-box
        fileWriter(errorMsg.ToString(), true); // call the file-writer function to write the error in a file
    }

    static void fileWriter(string fileText, bool append)
    {
        System.IO.StreamWriter file = new System.IO.StreamWriter(".\\Errorfile.txt", append); // locate the error next to the chat.exe
        file.WriteLine(GetTime(DateTime.Now) + "\n " + fileText); // append the date
        file.Close();
    }

    public static String GetTime(DateTime val)
    {
        return val.ToString("yyyyMMddHHmmssffff"); // return the current date as string
    }
}

}

1 个答案:

答案 0 :(得分:0)

而不是IPAddress.Broadcast(255.255.255.255)提供您的本地网络广播地址。请参阅以下示例:

IPAddress broadcast = IPAddress.Parse("192.168.1.255"); //replace the address with your local network.
IPEndPoint endPoint = new IPEndPoint(broadcast, 11000);
sendClient.Send(message, message.Length, endPoint);

IPAddress.Broadcast在某些网络中不起作用。