UDP 聊天功能的實現

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.Web;

namespace test
{
    public partial class Form1 : Form
    {
        private static UdpClient m_Client;
        private static int ListenerPort = 9000;
        private static int SenderPort = 9000;
        private static int LocalPort;
        private static int RemotePort;

        private static string m_szHostName;

        private static IPAddress m_GroupAddress_C;
        private static IPAddress m_GroupAddress_S;
        private static IPHostEntry m_LocalHost;
        private static IPEndPoint m_RemoteEP;

        private Thread th;

        public Form1()
        {
            InitializeComponent();
            //Control.CheckForIllegalCrossThreadCalls = false;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            LocalPort = SenderPort;
            RemotePort = ListenerPort;

            m_szHostName = Dns.GetHostName();

            m_LocalHost = Dns.GetHostByName(m_szHostName);

            textBox2.Text = m_LocalHost.AddressList[0].ToString();

            Initialize();

            th = new Thread(new ThreadStart(Listener));
            th.Start();

        }
       
        private void button1_Click(object sender, EventArgs e)
        {
            if (textBox1.Text.Trim() == "")
            {
                MessageBox.Show("發送字符不允許爲空");
                return;
            }

            m_GroupAddress_S = IPAddress.Parse(textBox2.Text); //要發送到的計算機IP
            m_RemoteEP = new IPEndPoint(m_GroupAddress_S, RemotePort);

            Byte[] buffer = null;

            Encoding ASCII = Encoding.ASCII;

            string s = HttpUtility.UrlEncode(textBox1.Text);
            textBox1.Text = "";

            buffer = new Byte[s.Length + 1];
            //
            // 將數據發送給遠程對方主機
            //

            int len = ASCII.GetBytes(s.ToCharArray(), 0, s.Length, buffer, 0);
           
            int ecode = m_Client.Send(buffer, len, m_RemoteEP);
           

        }

        public void Terminate()
        {
            m_Client.DropMulticastGroup(m_GroupAddress_C);
        }

        public void Initialize()
        {

            //
            // 實例化 UdpCLient
            //
            m_Client = new UdpClient(LocalPort);

            //
            // 創建對方主機的終結點
            //
            //m_GroupAddress_S = IPAddress.Parse("10.99.56.229"); //要發送到的計算機IP
            //m_RemoteEP = new IPEndPoint(m_GroupAddress_S, RemotePort);

        }

        public void Listener()
        {
            //
            // 創建多路廣播組對象
            //
            System.Net.IPHostEntry localhost = Dns.GetHostByName(Dns.GetHostName());
            string local_IP = localhost.AddressList[0].ToString();//接收消息的本地IP,用於監聽
            m_GroupAddress_C = IPAddress.Parse(local_IP);

            //
            // 聯接組
            //
            try
            {
                m_Client.JoinMulticastGroup(m_GroupAddress_C, 100); //不添加到多路廣播組也可以
            }
            catch (Exception err)
            {
                throw (err);//無法聯接多路廣播組
            }

            //
            // 偵聽器等待數據到來
            // 並用緩衝區保存它。

            Thread.Sleep(2000); // 確保 client2 正在接收

            Encoding ASCII = Encoding.ASCII;

            //    while(!m_Done)
            while (true)
            {
                IPEndPoint endpoint = null;
                endpoint = new IPEndPoint(m_GroupAddress_C,LocalPort);//這句代碼不要也可以
                try
                {
                    Byte[] data = m_Client.Receive(ref endpoint);

                    String strData = HttpUtility.UrlDecode(ASCII.GetString(data));

                    //listBox1.Items.Add(strData);
                    ReceiveCallBack rc = new ReceiveCallBack(writeReceive);
                    this.Invoke(rc, new object[] { strData });
                }
                catch(Exception ex)
                {
                    //throw ex;
                }
            }

        }
        private delegate void ReceiveCallBack(string str);
        public void writeReceive(string str)
        {
            listBox1.Items.Add(str);
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                try
                {
                    if (th != null)
                    {
                        if (th.IsAlive)
                        {
                            th.Abort();

                        }

                        th = null;

                    }

                }
                catch
                {
                    try
                    {
                        System.Threading.Thread.ResetAbort();
                    }
                    catch
                    { }
                }

                Terminate();
                m_Client.Close();
            }
            catch
            {
            }
        }

        private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                button1_Click(null, null);
            }
        }
       

    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章