简体   繁体   English

C#UDP聊天没有收到消息

[英]C# UDP Chat receive no message

I try to write a UDP-Chat in C#. 我尝试用C#编写UDP-Chat。

I have some unexpected behavoir in my Chat Programm, when I start the programm on two different machines connected to the same Network. 当我在连接到同一网络的两台不同的计算机上启动程序时,我的聊天程序中有一些意外的行为。 At the first mashine the programm works fine it can send and recive messages properly, but on the second machine it can just send messages but it can't recive them. 在第一个mashine上,程序可以正常运行,它可以正确发送和接收消息,但是在第二台计算机上,它只能发送消息,但不能接收消息。

I testet this with a 3rd mashine too(a VM with a bridged networkinterface), but with the same result, it just can send messages without recieving. 我也使用第三个mashine(具有桥接网络接口的VM)对此进行了测试,但是结果相同,它只是可以发送消息而不会接收。

is there a error in my code or is it a desing error? 我的代码中有错误还是设计错误?

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
    }
}

}

Instead of IPAddress.Broadcast(255.255.255.255) provide your local network broadcast address. 代替IPAddress.Broadcast(255.255.255.255)提供您的本地网络广播地址。 See the example below: 请参阅以下示例:

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 doesn't work in some network. IPAddress.Broadcast在某些网络中不起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM