多客户端聊天应用程序无法正常运行

时间:2015-01-29 22:20:21

标签: c# user-interface networking

我目前正在开发一个P2P聊天应用程序,该应用程序使用多播来在同一LAN上的用户之间传输数据(我正在使用D类IP地址)。这是我到目前为止编写的一些代码。

NetworkManager.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;

namespace WindowsFormsApp1
{
    /*
     *This class encapsulates the sending and receiving of the data using a Udp client
     */
    public class NetworkManager
    {
        private UdpClient client;
        private readonly string groupAddress = "230.0.0.1";
        private readonly int port = 8899;
        private byte[] data;
        private IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse("230.0.0.1"), 8899);
        private UnicodeEncoding encoding = new UnicodeEncoding();
        private bool joined //checks whether a client has joined a group or not;

        public NetworkManager()
        {
            client = new UdpClient(port);
            client.JoinMulticastGroup(IPAddress.Parse(groupAddress));
            joined = true;
        }
        public void Send(string msg)
        {
            byte[] bdata = encoding.GetBytes(msg);
            client.SendAsync(bdata, bdata.Length, remoteEP);
        }

        public string Receive()
        {
            IPEndPoint ep = null;
            data = client.Receive(ref ep);
            string msg = encoding.GetString(data);
            return msg;
        }

        public void Leave()
        {
            if (joined)
            {
                client.DropMulticastGroup(IPAddress.Parse(groupAddress));
                joined = false;
            }

        }

        public void Join()
        {
            if (!joined)
            {
                client.JoinMulticastGroup(IPAddress.Parse(groupAddress));
                joined = true;
            }
        }
    }
}

Form1.cs的

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {

        private NetworkManager ns;
        private string msg;
        private bool done;
        private string name;

        public Form1()
        {
            InitializeComponent();
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            //tboxName is where the user enters his/her name
            name = tboxName.Text;
            if (String.IsNullOrEmpty(name))
            {
                MessageBox.Show(this, "Enter a valid name", "Chat Form", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (ns == null)
            {
                ns = new NetworkManager();
            }
            else
            {
                ns.Join();
            }

            btnSend.Enabled = true;
            btnStart.Enabled = false;
            btnStop.Enabled = true;

            Task.Run(() => Listen());
            string s = String.Format("{0} has joined the chat.", name);
            ns.Send(s);


        }

        private void DisplayMessage()
        {
            string time = DateTime.Now.ToString("t");
            //tboxMsg is where the chat messages are displayed
            tboxMsg.Text += time + " " + msg + "\r\n";
        }

        private void Listen()
        {
            done = false;
            try
            {

                while (!done)
                {
                    msg = ns.Receive();
                    BeginInvoke(new Action(DisplayMessage));
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.ToString(), "Exception Occured", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnSend_Click(object sender, EventArgs e)
        {

            if (String.IsNullOrEmpty(tboxSend.Text)) return;
            string text = String.Format("{0}: {1}", name, tboxSend.Text);
            string time = DateTime.Now.ToString("t");
            tboxMsg.Text += time + " " + text + "\r\n";
            ns.Send(text);         
            tboxSend.Clear();
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            string s = String.Format("{0} has left the chat.", name);
            ns.Send(s);
            ns.Leave();
            btnSend.Enabled = false;
            btnStart.Enabled = true;
            btnStop.Enabled = false;

        }


    }
}

当我在同一台主机上使用不同端口值的两个不同的主机运行应用程序时,它可以正常工作,如下图所示: enter image description here 但是,当我从同一局域网上的两个不同主机运行它时,它似乎无法正常工作。它不接收或发送任何消息到远程主机。我只能在文本框中看到我正在写的内容和另一端的用户相同。我已经关闭了主机上的两个防火墙,但事实并非如此。以下是运行此案例的程序:     enter image description here 我在这做错了什么?为什么不在这种情况下工作?

提前致谢。

0 个答案:

没有答案