UDP聊天
2013-05-28 17:23 Carl Xing 阅读(177) 评论(0) 编辑 收藏 举报界面如下图,消息展示框,发送地址栏,和发送消息栏
打开程序会起一个线程接收消息。发送
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Net.Sockets; using System.Net; using System.Threading; namespace UdpChat { public partial class Form1 : Form { private UdpClient sendClient; private UdpClient receiveClient; Thread threadReceive, threadSend; private int receivePort = 2158; private int sendPort = 2675; private string LocalIp { get { IPAddress[] ips = Dns.GetHostAddresses(""); return ips[2].ToString(); } } public Form1() { InitializeComponent(); this.tbPort.Text = receivePort.ToString(); receiveClient = new UdpClient(receivePort);//new IPEndPoint(IPAddress.Parse(LocalIp),receivePort)); threadReceive = new Thread(new ThreadStart(ReceiveMessage)); threadReceive.Start(); } #region 接收消息 private void ReceiveMessage() { IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, 0); while (true) { try { // 关闭进程时此时会产生异常 byte[] receiveBuffer = receiveClient.Receive(ref endPoint); string message = endPoint.Address +":"+ System.Text.Encoding.UTF8.GetString(receiveBuffer); this.Invoke(new ListBoxAddMsgHandler(ListBoxAddMsg), new object[] { message }); } catch { threadSend.Abort(); break; } } } private delegate void ListBoxAddMsgHandler(object msg); /// <summary> /// 添加信息 /// </summary> /// <param name="msg"></param> private void ListBoxAddMsg(object msg) { listBox1.Items.Add(msg); } #endregion #region 发送消息 private void btnSend_Click(object sender, EventArgs e) { // 匿名模式(套接字绑定的端口由系统随机分配) sendClient = new UdpClient(0);//new IPEndPoint(IPAddress.Parse(LocalIp), sendPort)); threadSend = new Thread(SendMsg); threadSend.Start(tbMsg.Text); } private void SendMsg(object msg) { string message = msg.ToString(); byte[] msgBuffer = System.Text.Encoding.UTF8.GetBytes(message); try { IPEndPoint remoteIp=new IPEndPoint(IPAddress.Parse(tbIP.Text), int.Parse(tbPort.Text)); sendClient.Send(msgBuffer, msgBuffer.Length,remoteIp); } catch (Exception ex) { MessageBox.Show(ex.Message); } sendClient.Close(); this.Invoke(new CliearTextBoxHandler(ClearTextBox)); threadSend.Abort(); } private delegate void CliearTextBoxHandler(); private void ClearTextBox() { this.tbMsg.Text = string.Empty; } #endregion } }