C#UDP聊天没有收到消息 [英] C# UDP Chat receive no message

查看:83
本文介绍了C#UDP聊天没有收到消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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(带有桥接网络接口的VM)对此进行了测试,但是结果相同,它只能发送消息而不会接收。

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

}


推荐答案

代替IPAddress.Broadcast(255.255.255.255)提供您的本地网络广播地址。参见下面的示例:

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。广播在某些网络中不起作用。

IPAddress.Broadcast doesn't work in some network.

这篇关于C#UDP聊天没有收到消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆