简体   繁体   中英

C# UDP Chat receive no message

I try to write a UDP-Chat in C#.

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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