zoukankan      html  css  js  c++  java
  • 局域网QQ(C#版)

            本通讯程序没有服务端和客户端之分,局域网的计算机运行同一程序即可通信。
    由于水平有限,目前版本还很菜,只可以实现基本的聊天功能和显示在线用户功能。
    准备添加传送文件、聊天日志、可选参数等功能。

    using System;
    using System.Drawing;
    using System.Collections;
    using System.ComponentModel;
    using System.Windows.Forms;
    using System.Data;
    using System.Net;
    using System.Net.Sockets;
    using System.Text;
    using System.Threading;

    namespace myQQ
    {
     /// <summary>
     /// Form1 的摘要说明。
     /// </summary>
     public class Form1 : System.Windows.Forms.Form
     {
      public bool runing=false; //标志
      public UdpClient listen=new UdpClient(2525);
      public IPEndPoint End;
      public IPAddress groupAddress=IPAddress.Parse("255.255.255.255"); //广播地址
      public int groupPort=2525;  //广播端口
      public string machineName;
      public string machineIP;
      public string romeName;
      public string romeIP;
      public string romeCon;
     
      private System.Windows.Forms.ListBox box;
      private System.Windows.Forms.Label label1;
      private System.Windows.Forms.Label label2;
      private System.Windows.Forms.Button button1;
      private System.Windows.Forms.Button button3;
      private System.Windows.Forms.Label label3;
      private System.Windows.Forms.TextBox t_rec;
      private System.Windows.Forms.TextBox t_send;
      private System.Windows.Forms.Button button2;
      private System.Windows.Forms.Button newmsg;
      /// <summary>
      /// 必需的设计器变量。
      /// </summary>
      private System.ComponentModel.Container components = null;

      public Form1()
      {
       //
       // Windows 窗体设计器支持所必需的
       //
       InitializeComponent();

       //
       // TODO: 在 InitializeComponent 调用后添加任何构造函数代码
       //
      }

      /// <summary>
      /// 清理所有正在使用的资源。
      /// </summary>
      protected override void Dispose( bool disposing )
      {
       if( disposing )
       {
        if (components != null)
        {
         components.Dispose();
        }
       }
       base.Dispose( disposing );
      }

      #region Windows 窗体设计器生成的代码
      /// <summary>
      /// 设计器支持所需的方法 - 不要使用代码编辑器修改
      /// 此方法的内容。
      /// </summary>
      private void InitializeComponent()
      {
       this.box = new System.Windows.Forms.ListBox();
       this.t_rec = new System.Windows.Forms.TextBox();
       this.label1 = new System.Windows.Forms.Label();
       this.label2 = new System.Windows.Forms.Label();
       this.t_send = new System.Windows.Forms.TextBox();
       this.button1 = new System.Windows.Forms.Button();
       this.button3 = new System.Windows.Forms.Button();
       this.label3 = new System.Windows.Forms.Label();
       this.button2 = new System.Windows.Forms.Button();
       this.newmsg = new System.Windows.Forms.Button();
       this.SuspendLayout();
       //
       // box
       //
       this.box.ItemHeight = 12;
       this.box.Location = new System.Drawing.Point(0, 32);
       this.box.Name = "box";
       this.box.Size = new System.Drawing.Size(200, 352);
       this.box.TabIndex = 0;
       //
       // t_rec
       //
       this.t_rec.BackColor = System.Drawing.SystemColors.InactiveBorder;
       this.t_rec.ForeColor = System.Drawing.Color.FromArgb(((System.Byte)(192)), ((System.Byte)(64)), ((System.Byte)(0)));
       this.t_rec.Location = new System.Drawing.Point(208, 56);
       this.t_rec.Multiline = true;
       this.t_rec.Name = "t_rec";
       this.t_rec.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
       this.t_rec.Size = new System.Drawing.Size(328, 136);
       this.t_rec.TabIndex = 1;
       this.t_rec.Text = "";
       //
       // label1
       //
       this.label1.Location = new System.Drawing.Point(208, 40);
       this.label1.Name = "label1";
       this.label1.Size = new System.Drawing.Size(120, 16);
       this.label1.TabIndex = 2;
       this.label1.Text = "接收:";
       //
       // label2
       //
       this.label2.Location = new System.Drawing.Point(208, 200);
       this.label2.Name = "label2";
       this.label2.Size = new System.Drawing.Size(120, 16);
       this.label2.TabIndex = 2;
       this.label2.Text = "发送:";
       //
       // t_send
       //
       this.t_send.Location = new System.Drawing.Point(208, 216);
       this.t_send.Multiline = true;
       this.t_send.Name = "t_send";
       this.t_send.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
       this.t_send.Size = new System.Drawing.Size(328, 112);
       this.t_send.TabIndex = 1;
       this.t_send.Text = "";
       //
       // button1
       //
       this.button1.Location = new System.Drawing.Point(440, 344);
       this.button1.Name = "button1";
       this.button1.Size = new System.Drawing.Size(75, 32);
       this.button1.TabIndex = 3;
       this.button1.Text = "发  送";
       this.button1.Click += new System.EventHandler(this.button1_Click);
       //
       // button3
       //
       this.button3.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
       this.button3.Location = new System.Drawing.Point(88, 3);
       this.button3.Name = "button3";
       this.button3.Size = new System.Drawing.Size(56, 23);
       this.button3.TabIndex = 4;
       this.button3.Text = "刷 新";
       this.button3.Click += new System.EventHandler(this.button3_Click);
       //
       // label3
       //
       this.label3.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(134)));
       this.label3.ForeColor = System.Drawing.Color.Blue;
       this.label3.Location = new System.Drawing.Point(8, 8);
       this.label3.Name = "label3";
       this.label3.Size = new System.Drawing.Size(80, 16);
       this.label3.TabIndex = 5;
       this.label3.Text = "在线用户:";
       //
       // button2
       //
       this.button2.Location = new System.Drawing.Point(360, 344);
       this.button2.Name = "button2";
       this.button2.Size = new System.Drawing.Size(75, 32);
       this.button2.TabIndex = 6;
       this.button2.Text = "清  空";
       this.button2.Click += new System.EventHandler(this.button2_Click);
       //
       // newmsg
       //
       this.newmsg.Location = new System.Drawing.Point(208, 56);
       this.newmsg.Name = "newmsg";
       this.newmsg.Size = new System.Drawing.Size(328, 136);
       this.newmsg.TabIndex = 7;
       this.newmsg.Text = "有新消息了!";
       this.newmsg.Click += new System.EventHandler(this.newmsg_Click);
       //
       // Form1
       //
       this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
       this.ClientSize = new System.Drawing.Size(544, 389);
       this.Controls.Add(this.button2);
       this.Controls.Add(this.label3);
       this.Controls.Add(this.button3);
       this.Controls.Add(this.button1);
       this.Controls.Add(this.label1);
       this.Controls.Add(this.box);
       this.Controls.Add(this.label2);
       this.Controls.Add(this.t_send);
       this.Controls.Add(this.t_rec);
       this.Controls.Add(this.newmsg);
       this.Name = "Form1";
       this.Text = "小y";
       this.Closing += new System.ComponentModel.CancelEventHandler(this.Form1_Closing);
       this.Load += new System.EventHandler(this.Form1_Load);
       this.ResumeLayout(false);

      }
      #endregion

      /// <summary>
      /// 应用程序的主入口点。
      /// </summary>
      [STAThread]
      static void Main()
      {
       Application.Run(new Form1());
      }

      private void Form1_Load(object sender, System.EventArgs e)
      {
      
      
       End=new IPEndPoint(groupAddress,groupPort);
       //初始化计算机名和端口
       IPHostEntry myentry=Dns.GetHostByName(Dns.GetHostName());
       IPAddress myaddress=new IPAddress(myentry.AddressList[0].Address);
       machineName=Dns.GetHostName();
       machineIP=myaddress.ToString();

       box.Items.Add("IP            主机名");

       //开启监听线程
       runing=true;
       Thread myThread=new Thread(new ThreadStart(this.ListenPort));
       myThread.Start();

       //发送上线信息
       string sends="0&"+machineIP+"&"+machineName+"&"+machineIP;
       SendPack(sends);
      }

      //侦听指定端口的广播地址UDP包
      public void ListenPort()
      {
       IPEndPoint tempEnd=new IPEndPoint(IPAddress.Any,2525);
       while(runing)
       {
        Application.DoEvents();
        try
        {
         byte[] recb=listen.Receive(ref tempEnd);

         // 检查所接收到的信息
         checkMessage(recb);
        }
        catch(Exception e)
        {
         MessageBox.Show(e.Message.ToString());
         break;
        }
       
       }
       listen.Close();
       box.Items.Add("线程已经退出!");
       runing=false;
      }

      //循环接收包
      public void checkMessage(byte[] recbb)
      {
       string recStr=Encoding.Default.GetString(recbb);
       string[] rec=recStr.Split('&');
       switch(rec[0])
       {
        case "0": //刷新
         if(rec[3]==machineIP)
         {
          if(box.FindString(rec[1]+"  "+rec[2])<=0)
               box.Items.Add(rec[1]+"  "+rec[2]);
         }
         else  if(rec[1]==rec[3])
         {
          //从其他机器发送过来的刷新请求
          //返回自己的信息
          string sendstr="0&"+machineIP+"&"+machineName+"&"+rec[3];
          this.SendPack(sendstr);
          //如果不存在则添加该用户
          if(box.FindString(rec[1]+"  "+rec[2])<=0)
           box.Items.Add(rec[1]+"  "+rec[2]);
         }
         break;
        case "1": //发言
         if(rec[3]==machineIP)
         {
          romeName=rec[2];
          romeIP=rec[1];
          romeCon=rec[4];
          showNe();
         }
         break;
        case "2": //传文件
         break;
        case "9": //确认包
         if(rec[3]==machineIP)
          MessageBox.Show("信息来自:rec[2]("+rec[1]+")\r\n"+rec[4],"消息");
         break;
       }
      
      }
          
      //发送数据包到广播地址
      public void SendPack(string sendStr)
      {
      
       byte[] sendb=Encoding.Default.GetBytes(sendStr);
       try
       {
        listen.Send(sendb,sendb.Length,End);
       }
       catch(Exception e)
       {
        MessageBox.Show(e.Message.ToString());
       }
      }


      //刷新
      private void button3_Click(object sender, System.EventArgs e)
      {
       box.Items.Clear();
       box.Items.Add("IP            主机名");
       string temp2="0&"+machineIP+"&"+machineName+"&"+machineIP;
       this.SendPack(temp2);
      }

      //关闭循环
      private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
      {
       runing=false;
       UdpClient mm=new UdpClient();
       IPEndPoint tempIPEnd=new IPEndPoint(IPAddress.Parse("127.0.0.1"),2525);
       string temps="0&0&0&0&0";
       byte[] sendb=Encoding.Default.GetBytes(temps);
       mm.Send(sendb,sendb.Length,tempIPEnd);
      }
      //发送
      private void button1_Click(object sender, System.EventArgs e)
      {
       if(t_send.Text=="")
       {
        MessageBox.Show("不能发送空信息!");
        return;
       }
       if(box.SelectedItem==null||box.SelectedIndex==0)
       {
        MessageBox.Show("请先选择一个用户!");
        return;
       }
       string send="1&"+machineIP+"&"+machineName+"&"+box.SelectedItem.ToString().Split(' ')[0]+"&"+t_send.Text;
       this.SendPack(send);
      }
      //清空
      private void button2_Click(object sender, System.EventArgs e)
      {
       t_send.Text=string.Empty;
       t_rec.Text=string.Empty;
      }
      //单击显示接收的信息并隐藏自身
      private void newmsg_Click(object sender, System.EventArgs e)
      {
       t_rec.Text="消息来自"+romeName+"("+romeIP+")"+DateTime.Now.ToShortDateString();
       t_rec.Text+="\r\n> "+romeCon;
       string back="9&"+machineIP+"&"+machineName+"&"+romeIP+"&信息被打开!";
       this.SendPack(back);
       newmsg.SendToBack();

      }
      //当有信息时显示提示按钮
      public void showNe()
      {
       //窗体显示
       if(this.WindowState!=FormWindowState.Normal)
       {
        this.Visible=true;
        this.WindowState=FormWindowState.Normal;
       }
       newmsg.BringToFront();
      }
     }
    }

  • 相关阅读:
    Java实现 LeetCode 34 在排序数组中查找元素的第一个和最后一个位置
    Java实现 LeetCode 34 在排序数组中查找元素的第一个和最后一个位置
    MFC的消息映射机制揭秘
    vc++窗口的创建过程(MFC消息机制的经典文章)
    映射窗口句柄对象
    评侯捷的<深入浅出MFC>和李久进的<MFC深入浅出>
    主函数 main WinMain _tmain _tWinMain 的区别
    深入分析MFC文档视图结构(项目实践)
    深入解析MFC -- 句柄与对象的关系
    深入浅出Win32多线程设计之MFC的多线程-线程与消息队列(经典)
  • 原文地址:https://www.cnblogs.com/tuyile006/p/507677.html
Copyright © 2011-2022 走看看