C#利用组播实现网络会议室功能(即群聊功能)

C#利用组播实现群发功能

 

[csharp]  view plain copy
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel;  
  4. using System.Data;  
  5. using System.Drawing;  
  6. using System.Text;  
  7. using System.Windows.Forms;  
  8. //添加的命名空间引用  
  9. using System.Net;  
  10. using System.Net.Sockets;  
  11. using System.Threading;  
  12.   
  13. namespace NetMeetingExample  
  14. {  
  15.     public partial class FormMeeting : Form  
  16.     {  
  17.         private enum ListBoxOperation { AddItem, RemoveItem };  
  18.         private delegate void SetListBoxItemCallback(  
  19.             ListBox listbox, string text, ListBoxOperation operation);  
  20.         SetListBoxItemCallback listBoxCallback;  
  21.         //使用的IP地址  
  22.         private IPAddress broderCastIp = IPAddress.Parse("224.100.0.1");  
  23.         //使用的接收端口号  
  24.         private int port = 8001;  
  25.         private UdpClient udpClient;  
  26.         public FormMeeting()  
  27.         {  
  28.             InitializeComponent();  
  29.             listBoxCallback = new SetListBoxItemCallback(SetListBoxItem);  
  30.         }  
  31.         private void SetListBoxItem(ListBox listbox, string text, ListBoxOperation operation)  
  32.         {  
  33.             if (listbox.InvokeRequired == true)  
  34.             {  
  35.                 this.Invoke(listBoxCallback, listbox, text, operation);  
  36.             }  
  37.             else  
  38.             {  
  39.                 if (operation == ListBoxOperation.AddItem)  
  40.                 {  
  41.                     if (listbox == listBoxAddress)  
  42.                     {  
  43.                         if (listbox.Items.Contains(text) == false)  
  44.                         {  
  45.                             listbox.Items.Add(text);  
  46.                         }  
  47.                     }  
  48.                     else  
  49.                     {  
  50.                         listbox.Items.Add(text);  
  51.                     }  
  52.                     listbox.SelectedIndex = listbox.Items.Count - 1;  
  53.                     listbox.ClearSelected();  
  54.                 }  
  55.                 else if (operation == ListBoxOperation.RemoveItem)  
  56.                 {  
  57.                     listbox.Items.Remove(text);  
  58.                 }  
  59.             }  
  60.         }  
  61.   
  62.   
  63.         private void FormMeeting_Load(object sender, EventArgs e)  
  64.         {  
  65.             listBoxMessage.HorizontalScrollbar = true;  
  66.             buttonLogin.Enabled = true;  
  67.             buttonLogout.Enabled = false;  
  68.             groupBoxRoom.Enabled = false;  
  69.         }  
  70.   
  71.         //单击进入会议室按钮触发的事件  
  72.         private void buttonLogin_Click(object sender, EventArgs e)  
  73.         {  
  74.             Cursor.Current = Cursors.WaitCursor;//修改当前光标形状  
  75.             Thread myThread = new Thread(ReceiveMessage);  
  76.             myThread.Start();  
  77.             //等待接收线程准备完毕  
  78.             Thread.Sleep(1000);  
  79.             SendMessage(broderCastIp, "Login");  
  80.             buttonLogin.Enabled = false;  
  81.             buttonLogout.Enabled = true;  
  82.             groupBoxRoom.Enabled = true;  
  83.             Cursor.Current = Cursors.Default;//恢复光标形状为默认形状(即指针状)  
  84.         }  
  85.   
  86.         /// <summary>  
  87.         /// 接收线程  
  88.         /// </summary>  
  89.         private void ReceiveMessage()  
  90.         {  
  91.             udpClient = new UdpClient(port);  
  92.             //必须使用组播地址范围内的地址  
  93.             udpClient.JoinMulticastGroup(broderCastIp);//加入组播地址为broderCastIp的组播中,这样就可以接收该组播中的所有消息了  
  94.             udpClient.Ttl = 50;  
  95.             IPEndPoint remote = null;  
  96.             while (true)  
  97.             {  
  98.                 try  
  99.                 {  
  100.                     //关闭udpClient时此句会产生异常  
  101.                     byte[] bytes = udpClient.Receive(ref remote);//remote用于接收远程主机的IP地址  
  102.                     string str = Encoding.UTF8.GetString(bytes, 0, bytes.Length);  
  103.                     string[] splitString = str.Split(',');  
  104.                     int s = splitString[0].Length;  
  105.                     switch (splitString[0])  
  106.                     {  
  107.                         case "Login":  //进入会议室   
  108.                             SetListBoxItem(listBoxMessage,  
  109.                                 string.Format("[{0}]进入。", remote.Address), ListBoxOperation.AddItem);  
  110.                             SetListBoxItem(listBoxAddress,  
  111.                             remote.Address.ToString(), ListBoxOperation.AddItem);  
  112.                             string userListString = "List," + remote.Address.ToString();  
  113.                             for (int i = 0; i < listBoxAddress.Items.Count; i++)  
  114.                             {  
  115.                                 userListString += "," + listBoxAddress.Items[i].ToString();  
  116.                             }  
  117.                             SendMessage(remote.Address, userListString);  
  118.                             break;  
  119.                         case "List"//参加会议人员名单  
  120.                             for (int i = 1; i < splitString.Length; i++)  
  121.                             {  
  122.                                 SetListBoxItem(listBoxAddress,  
  123.                                     splitString[i], ListBoxOperation.AddItem);  
  124.                             }  
  125.                             break;  
  126.                         case "Message":  //发言内容  
  127.                             SetListBoxItem(listBoxMessage,  
  128.                                 string.Format("[{0}]说:{1}", remote.Address, str.Substring(8)),  
  129.                                 ListBoxOperation.AddItem);  
  130.                             break;  
  131.                         case "Logout"//退出会议室  
  132.                             SetListBoxItem(listBoxMessage,  
  133.                                 string.Format("[{0}]退出。", remote.Address),  
  134.                                 ListBoxOperation.AddItem);  
  135.                             SetListBoxItem(listBoxAddress,  
  136.                                 remote.Address.ToString(), ListBoxOperation.RemoveItem);  
  137.                             break;  
  138.                     }  
  139.                 }  
  140.                 catch  
  141.                 {  
  142.                     //退出循环,结束线程  
  143.                     break;  
  144.                 }  
  145.             }  
  146.         }  
  147.   
  148.         //响应回车键发送消息  
  149.         private void textBoxMessage_KeyPress(object sender, KeyPressEventArgs e)  
  150.         {  
  151.             if (e.KeyChar == (char)Keys.Return)//如果按了回车键则发送信息  
  152.             {  
  153.                 if (textBoxMessage.Text.Trim().Length > 0)  
  154.                 {  
  155.                     SendMessage(broderCastIp, "Message," + textBoxMessage.Text);//发送信息通过组播地址broderCastIp发送  
  156.                     textBoxMessage.Text = "";  
  157.                 }  
  158.             }  
  159.         }  
  160.   
  161.         private void SendMessage(IPAddress ip, string sendString)  
  162.         {  
  163.             UdpClient myUdpClient = new UdpClient();  
  164.             //允许发送和接收广播数据报  
  165.             // myUdpClient.EnableBroadcast = true;  
  166.             //必须使用组播地址范围内的地址  
  167.             IPEndPoint iep = new IPEndPoint(ip, port);  
  168.             //将发送内容转换为字节数组  
  169.             byte[] bytes = System.Text.Encoding.UTF8.GetBytes(sendString);  
  170.             try  
  171.             {  
  172.                 //向子网发送信息  
  173.                 myUdpClient.Send(bytes, bytes.Length, iep);  
  174.             }  
  175.             catch (Exception err)  
  176.             {  
  177.                 MessageBox.Show(err.Message, "发送失败");  
  178.             }  
  179.             finally  
  180.             {  
  181.                 myUdpClient.Close();  
  182.             }  
  183.         }  
  184.          
  185.   
  186.         //单击退出会议室按钮触发的事件  
  187.         private void buttonLogout_Click(object sender, EventArgs e)  
  188.         {  
  189.             Cursor.Current = Cursors.WaitCursor;  
  190.             SendMessage(broderCastIp, "Logout");  
  191.             udpClient.DropMulticastGroup(this.broderCastIp);//退出组播  
  192.   
  193.             //等待接收线程处理完毕  
  194.             Thread.Sleep(1000);  
  195.   
  196.             //结束接收线程  
  197.             udpClient.Close();  
  198.             buttonLogin.Enabled = true;  
  199.             buttonLogout.Enabled = false;  
  200.             groupBoxRoom.Enabled = false;  
  201.             Cursor.Current = Cursors.Default;  
  202.         }  
  203.   
  204.         //窗体已关闭并指定关闭原因前触发的事件  
  205.         private void Form1_FormClosing(object sender, FormClosingEventArgs e)  
  206.         {  
  207.             if (buttonLogout.Enabled == true)  
  208.             {  
  209.                 MessageBox.Show("请先离开会议室,然后再退出!""",  
  210.                     MessageBoxButtons.OK, MessageBoxIcon.Warning);  
  211.                 //不关闭窗体  
  212.                 e.Cancel = true;  
  213.             }  
  214.         }  
  215.   
  216.     }  
  217. }  


界面设计:

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值