局域网QQ第三版(V1.4)-程序员宅基地

技术标签: 局域网  

原文地址为: 局域网QQ第三版(V1.4)

局域网QQ,无客户端和服务端之分,局域网的计算机运行本程序就可以互相看见,可以自由聊天和传文件。

本版较之1.0版的改进之处:
     使用数据结构类型传送数据;
     增加传文件功能(有进度条);

考虑大家重现本程序方便,本程序一直没有用到任何额外的控件和子窗体
版本依然是在VS2003下编译,只要贴进编译器中就可以重现。
转换到VS2005平台的方法:
把程序拷到vs2005中form1.cs里面
在“窗体设计器生成的代码”里面加一句:
System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;
然后把vs2005自动生成的form1.designer.cs 和program.cs两个文件删掉


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;
using System.IO;

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 IPAddress myIP;
        public string myName;
        public string romeName;
        public IPAddress romeIP;
        public string romeCon;
        public sendData mySendData = new sendData(); //本地的0号命令发送包
        public bool isfile;//传送文件标志
        public string savePath;//传文件的保存地址
        public string romeFileName;//远程文件名
        public string romeFilel;//远程文件用单位表示的长度,格式为 43M或437K
        public FileStream sendfilestream;//发送文件流

        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.TextBox t_rec;
        private System.Windows.Forms.TextBox t_send;
        private System.Windows.Forms.Button button2;
        private System.Windows.Forms.Button newmsg;
        private System.Windows.Forms.Label online;
        private System.Windows.Forms.ToolTip toolTip1;
        //private System.Windows.Forms.ImageList imageList1;
        private System.Windows.Forms.LinkLabel linkLabel1;
        private System.Windows.Forms.Label label3;
        private System.Windows.Forms.Button button4;
        private System.Windows.Forms.OpenFileDialog openFileDialog1;
        private System.Windows.Forms.TextBox t_filep;
        private System.Windows.Forms.SaveFileDialog saveFileDialog1;
        private System.Windows.Forms.Panel processA;
        private System.Windows.Forms.ProgressBar progressBar1;
        private System.Windows.Forms.Panel processB;
        private System.Windows.Forms.ProgressBar progressBar2;
        private System.ComponentModel.IContainer components;

        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()
        {
            //System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;
            this.components = new System.ComponentModel.Container();
            System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(Form1));
            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.online = new System.Windows.Forms.Label();
            this.button2 = new System.Windows.Forms.Button();
            this.newmsg = new System.Windows.Forms.Button();
            this.toolTip1 = new System.Windows.Forms.ToolTip(this.components);
            //this.imageList1 = new System.Windows.Forms.ImageList(this.components);
            this.linkLabel1 = new System.Windows.Forms.LinkLabel();
            this.label3 = new System.Windows.Forms.Label();
            this.t_filep = new System.Windows.Forms.TextBox();
            this.button4 = new System.Windows.Forms.Button();
            this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
            this.saveFileDialog1 = new System.Windows.Forms.SaveFileDialog();
            this.processA = new System.Windows.Forms.Panel();
            this.progressBar1 = new System.Windows.Forms.ProgressBar();
            this.processB = new System.Windows.Forms.Panel();
            this.progressBar2 = new System.Windows.Forms.ProgressBar();
            this.processA.SuspendLayout();
            this.processB.SuspendLayout();
            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(48, 16);
            this.label2.TabIndex = 2;
            this.label2.Text = "发送:";
            //
            // t_send
            //
            this.t_send.Location = new System.Drawing.Point(208, 224);
            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, 120);
            this.t_send.TabIndex = 1;
            this.t_send.Text = "";
            //
            // button1
            //
            this.button1.Location = new System.Drawing.Point(440, 352);
            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(120, 5);
            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);
            //
            // online
            //
            this.online.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(134)));
            this.online.ForeColor = System.Drawing.Color.Blue;
            this.online.Location = new System.Drawing.Point(8, 8);
            this.online.Name = "online";
            this.online.Size = new System.Drawing.Size(88, 16);
            this.online.TabIndex = 5;
            this.online.Text = "在线用户:";
            //
            // button2
            //
            this.button2.Location = new System.Drawing.Point(352, 352);
            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);
            //
            // imageList1
            //
            //this.imageList1.ImageSize = new System.Drawing.Size(32, 32);
            //this.imageList1.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList1.ImageStream")));
            //this.imageList1.TransparentColor = System.Drawing.Color.Transparent;
            //
            // linkLabel1
            //
            this.linkLabel1.Location = new System.Drawing.Point(264, 200);
            this.linkLabel1.Name = "linkLabel1";
            this.linkLabel1.Size = new System.Drawing.Size(48, 16);
            this.linkLabel1.TabIndex = 8;
            this.linkLabel1.TabStop = true;
            this.linkLabel1.Text = "传文件";
            this.linkLabel1.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel1_LinkClicked);
            //
            // label3
            //
            this.label3.Location = new System.Drawing.Point(208, 240);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(72, 16);
            this.label3.TabIndex = 9;
            this.label3.Text = "文件地址:";
            //
            // t_filep
            //
            this.t_filep.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.t_filep.Location = new System.Drawing.Point(272, 232);
            this.t_filep.Name = "t_filep";
            this.t_filep.Size = new System.Drawing.Size(233, 21);
            this.t_filep.TabIndex = 10;
            this.t_filep.Text = "";
            //
            // button4
            //
            this.button4.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
            this.button4.Location = new System.Drawing.Point(504, 232);
            this.button4.Name = "button4";
            this.button4.Size = new System.Drawing.Size(32, 21);
            this.button4.TabIndex = 11;
            this.button4.Text = "…";
            this.button4.Click += new System.EventHandler(this.button4_Click);
            //
            // processA
            //
            this.processA.BackColor = System.Drawing.SystemColors.Window;
            this.processA.Controls.Add(this.progressBar1);
            this.processA.Location = new System.Drawing.Point(224, 264);
            this.processA.Name = "processA";
            this.processA.Size = new System.Drawing.Size(288, 24);
            this.processA.TabIndex = 12;
            //
            // progressBar1
            //
            this.progressBar1.Location = new System.Drawing.Point(8, 6);
            this.progressBar1.Name = "progressBar1";
            this.progressBar1.Size = new System.Drawing.Size(272, 12);
            this.progressBar1.Step = 5;
            this.progressBar1.TabIndex = 0;
            //
            // processB
            //
            this.processB.BackColor = System.Drawing.SystemColors.Control;
            this.processB.Controls.Add(this.progressBar2);
            this.processB.Location = new System.Drawing.Point(224, 112);
            this.processB.Name = "processB";
            this.processB.Size = new System.Drawing.Size(288, 24);
            this.processB.TabIndex = 12;
            //
            // progressBar2
            //
            this.progressBar2.Location = new System.Drawing.Point(8, 6);
            this.progressBar2.Name = "progressBar2";
            this.progressBar2.Size = new System.Drawing.Size(272, 12);
            this.progressBar2.Step = 5;
            this.progressBar2.TabIndex = 0;
            //
            // Form1
            //
            this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
            this.ClientSize = new System.Drawing.Size(544, 389);
            this.Controls.Add(this.processB);
            this.Controls.Add(this.processA);
            this.Controls.Add(this.t_send);
            this.Controls.Add(this.button4);
            this.Controls.Add(this.t_filep);
            this.Controls.Add(this.label3);
            this.Controls.Add(this.linkLabel1);
            this.Controls.Add(this.button2);
            this.Controls.Add(this.online);
            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_rec);
            this.Controls.Add(this.newmsg);
            //this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.Name = "Form1";
            this.Text = "小y";
            this.Closing += new System.ComponentModel.CancelEventHandler(this.Form1_Closing);
            this.Load += new System.EventHandler(this.Form1_Load);
            this.processA.ResumeLayout(false);
            this.processB.ResumeLayout(false);
            this.ResumeLayout(false);

        }
        #endregion

        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.Run(new Form1());
        }
        //数据包格式
        public struct sendData
        {
            public byte commandNo;//命令号 1字节
            public IPAddress fromIP;//发送端IP 4字节
            public int nameLength;  //名字的字节数  4字节
            public string computerName;//计算机名  x字节
            public IPAddress toIP;//接收端IP; 4字节
            public string content;//内容  y字节
        }
        private void Form1_Load(object sender, System.EventArgs e)
        {

            End = new IPEndPoint(groupAddress, groupPort);
            //初始化计算机名和端口
            IPHostEntry myentry = Dns.GetHostByName(Dns.GetHostName());
            myIP = new IPAddress(myentry.AddressList[0].Address);
            myName = Dns.GetHostName();

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

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

            //发送上线信息
            mySendData.commandNo = 0;
            mySendData.fromIP = myIP;
            mySendData.computerName = myName;
            mySendData.toIP = myIP;
            mySendData.content = "上线提示";
            byte[] sendb = StructToBytes(mySendData);
            SendPack(sendb);

            //初始化窗体位置
            t_send.Height = 120;
            t_send.Top = 224;
            linkLabel1.Text = "传文件";
            processA.Visible = false;//发送的进度
            processB.Visible = false;//接收的进度
        }

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

                    // 检查所接收到的信息and处理之
                    checkMessage(recb);
                }
                catch (Exception e)
                {
                    MessageBox.Show("出现错误:" + e.Message.ToString());
                    break;
                }

            }
            listen.Close();
            box.Items.Add("线程已经退出!");
            runing = false;
        }

        //循环接收包
        public void checkMessage(byte[] recbb)
        {
            sendData recData = BytesToStruct(recbb);
            romeName = recData.computerName;
            romeIP = recData.fromIP;
            romeCon = recData.content;
            switch (recData.commandNo)
            {
                case 0x00: //刷新
                    if (recData.toIP.Equals(myIP))
                    {
                        if (box.FindString(recData.fromIP.ToString() + "  " + recData.computerName) <= 0)
                            box.Items.Add(recData.fromIP.ToString() + "  " + recData.computerName);
                        online.Text = "在线用户:" + (box.Items.Count - 1) + "人";
                    }
                    else if (recData.fromIP.Equals(recData.toIP))
                    {
                        //从其他机器发送过来的刷新请求
                        //返回自己的信息
                        mySendData.commandNo = 0x00;
                        mySendData.toIP = recData.toIP;
                        mySendData.content = "上线提示";
                        byte[] sendb = StructToBytes(mySendData);
                        SendPack(sendb);
                        //如果不存在则添加该用户
                        if (box.FindString(recData.fromIP.ToString() + "  " + recData.computerName) <= 0)
                            box.Items.Add(recData.fromIP.ToString() + "  " + recData.computerName);
                    }
                    break;
                case 0x01: //发言
                    if (recData.toIP.Equals(myIP) && !isfile)
                    {//当传送的不包含文件时才显示“有新消息了”
                        showNe();
                    }
                    break;
                case 0x02: //请求传文件
                    if (recData.toIP.Equals(myIP))
                    {//准备接收文件
                        romeFileName = romeCon.Split('+')[0];
                        romeFilel = romeCon.Split('+')[1];
                        readyRecFile();
                    }
                    break;
                case 0x03://传文件
                    if (recData.toIP.Equals(myIP))
                    {//传送文件
                        Thread mysend = new Thread(new ThreadStart(sendFile));
                        mysend.Start();
                    }
                    break;
                case 0x09: //确认包
                    if (recData.toIP.Equals(myIP))
                        MessageBox.Show("信息来自:" + recData.computerName + "(" + recData.fromIP.ToString() + ")\r\n" + recData.content, "消息");
                    break;
            }

        }

        //发送数据包到广播地址
        public void SendPack(byte[] sendbs)
        {
            try
            {
                listen.Send(sendbs, sendbs.Length, End);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message.ToString());
            }
        }
        //struct转换成byte[]
        public static byte[] StructToBytes(sendData structObj)
        {
            byte[] commandb = new byte[1];
            commandb[0] = structObj.commandNo;
            byte[] fromipb = structObj.fromIP.GetAddressBytes();
            byte[] nameb = Encoding.Default.GetBytes(structObj.computerName);
            byte[] lengthb = BitConverter.GetBytes(nameb.Length);
            byte[] toipb = structObj.toIP.GetAddressBytes();
            byte[] contentb = Encoding.Default.GetBytes(structObj.content);
            byte[] buffer = new byte[13 + nameb.Length + contentb.Length];
            int index = 0;
            commandb.CopyTo(buffer, index);
            index += commandb.Length;
            fromipb.CopyTo(buffer, index);
            index += fromipb.Length;
            lengthb.CopyTo(buffer, index);
            index += lengthb.Length;
            nameb.CopyTo(buffer, index);
            index += nameb.Length;
            toipb.CopyTo(buffer, index);
            index += toipb.Length;
            contentb.CopyTo(buffer, index);
            return buffer;
        }
        //byte转换成struct
        public static sendData BytesToStruct(byte[] bytes)
        {
            sendData myre = new sendData();
            myre.commandNo = bytes[0];
            byte[] ipb = new byte[4];
            Array.Copy(bytes, 1, ipb, 0, 4);
            myre.fromIP = IPAddress.Parse(ipByteToString(ipb));
            myre.nameLength = BitConverter.ToInt32(bytes, 5);
            myre.computerName = Encoding.Default.GetString(bytes, 9, myre.nameLength);
            Array.Copy(bytes, 9 + myre.nameLength, ipb, 0, 4);
            myre.toIP = IPAddress.Parse(ipByteToString(ipb));
            myre.content = Encoding.Default.GetString(bytes, 13 + myre.nameLength, bytes.Length - 13 - myre.nameLength);
            return myre;
        }
        //将byte[]表示的IP地址转换成IPAddress类型
        public static string ipByteToString(byte[] ipbt)
        {
            string temp = "";
            temp = (int)ipbt[0] + "." + (int)ipbt[1] + "." + (int)ipbt[2] + "." + (int)ipbt[3];
            return temp;
        }
        //刷新
        private void button3_Click(object sender, System.EventArgs e)
        {
            box.Items.Clear();
            box.Items.Add("IP            主机名");
            mySendData.commandNo = 0;
            mySendData.fromIP = myIP;
            mySendData.computerName = myName;
            mySendData.toIP = myIP;
            mySendData.content = "上线提示";
            byte[] sendb = StructToBytes(mySendData);
            SendPack(sendb);
        }

        //关闭循环
        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);
            mySendData.commandNo = 0;
            mySendData.fromIP = myIP;
            mySendData.computerName = myName;
            mySendData.toIP = myIP;
            mySendData.content = "上线提示";
            byte[] sendb = StructToBytes(mySendData);
            mm.Send(sendb, sendb.Length, tempIPEnd);
        }
        //发送
        private void button1_Click(object sender, System.EventArgs e)
        {
            if (box.SelectedItem == null || box.SelectedIndex == 0)
            {
                MessageBox.Show("请先选择一个用户!");
                return;
            }
            if (linkLabel1.Text == "不传文件" && t_filep.Text != "")
            {//需要传文件
                //首先发送2号命令 要求对方准备接收
                sendfilestream = new FileStream(t_filep.Text, FileMode.Open, FileAccess.Read);
                long filelength = sendfilestream.Length;
                string totalsteps;
                int temp;
                if (filelength / (1024 * 1024) > 10)
                {//文件>10M时用M做为进度最小单位
                    temp = (int)(filelength / (1024 * 1024));
                    totalsteps = temp + "M";
                }
                else
                {//小于10M的文件用k做为最小单位
                    temp = (int)(filelength / 1024);
                    totalsteps = temp + "K";
                }
                //用做接收端时的公共变量保存发送的临时值
                romeFilel = totalsteps;
                string filename = Path.GetFileName(t_filep.Text);
                mySendData.commandNo = 0x02;
                mySendData.fromIP = myIP;
                mySendData.computerName = myName;
                mySendData.toIP = IPAddress.Parse(box.SelectedItem.ToString().Split(' ')[0]);
                mySendData.content = filename + "+" + totalsteps;//格式:yy.txt+62K+64990
                byte[] sendb = StructToBytes(mySendData);
                SendPack(sendb);

                //界面上的处理
                t_send.Height = 120;
                t_send.Top = 224;
                linkLabel1.Text = "传文件";
            }
            //发言
            if (t_send.Text == "")
            {
                return;
            }
            mySendData.commandNo = 0x01;
            mySendData.fromIP = myIP;
            mySendData.computerName = myName;
            mySendData.toIP = IPAddress.Parse(box.SelectedItem.ToString().Split(' ')[0]);
            mySendData.content = t_send.Text;
            byte[] sendb2 = StructToBytes(mySendData);
            SendPack(sendb2);
        }
        //清空
        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)
        {
            if (isfile)
            {//当传送的含有文件时
                saveFileDialog1.Filter = "所有格式|*.*";
                saveFileDialog1.FileName = romeFileName;
                if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                    savePath = saveFileDialog1.FileName;
                else
                    return;
                t_rec.Text = "消息来自" + romeName + "(" + romeIP.ToString() + ")" + DateTime.Now.ToShortDateString();
                t_rec.Text += "\r\n> " + romeCon;
                //界面的处理
                newmsg.SendToBack();
                t_send.Height = 120;
                t_send.Top = 224;
                linkLabel1.Text = "传文件";
                //返回一个确认接收包
                mySendData.commandNo = 0x03;
                mySendData.fromIP = myIP;
                mySendData.computerName = myName;
                mySendData.toIP = romeIP;
                mySendData.content = "ready!";
                byte[] sendb = StructToBytes(mySendData);
                SendPack(sendb);
                //复位文件标志
                isfile = false;
                //同时开启线程开始监听
                Thread myrecv = new Thread(new ThreadStart(listenPort));
                myrecv.Start();
                return;
            }
            t_rec.Text = "消息来自" + romeName + "(" + romeIP.ToString() + ")" + DateTime.Now.ToShortDateString();
            t_rec.Text += "\r\n> " + romeCon;
            mySendData.commandNo = 0x09;
            mySendData.toIP = romeIP;
            mySendData.content = "信息被打开!";
            byte[] sendb2 = StructToBytes(mySendData);
            SendPack(sendb2);
            newmsg.SendToBack();
        }
        //当有信息时显示提示按钮
        public void showNe()
        {
            //窗体显示
            if (this.WindowState != FormWindowState.Normal)
            {
                this.Visible = true;
                this.WindowState = FormWindowState.Normal;
            }
            newmsg.Text = "有新消息了";
            newmsg.BringToFront();
        }
        //准备接收文件
        public void readyRecFile()
        {
            //窗体显示
            if (this.WindowState != FormWindowState.Normal)
            {
                this.Visible = true;
                this.WindowState = FormWindowState.Normal;
            }
            isfile = true;
            newmsg.Text = romeFileName + "(" + romeFilel + ")";
            newmsg.BringToFront();
        }
        //传文件
        private void linkLabel1_LinkClicked(object sender, System.Windows.Forms.LinkLabelLinkClickedEventArgs e)
        {
            if (linkLabel1.Text == "传文件")
            {
                t_send.Height = 80;
                t_send.Top = 264;
                linkLabel1.Text = "不传文件";
            }
            else
            {
                t_send.Height = 120;
                t_send.Top = 224;
                linkLabel1.Text = "传文件";
            }
        }
        //打开文件
        private void button4_Click(object sender, System.EventArgs e)
        {
            openFileDialog1.Filter = "所有文件|*.*|压缩文件|*.rar";
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                t_filep.Text = openFileDialog1.FileName;
            }
        }

        //监听文件传送socket的线程——————功能:接收文件
        public void listenPort()
        {
            TcpListener listener = new TcpListener(2626);
            listener.Start();
            Socket s = listener.AcceptSocket();
            FileStream filestream = new FileStream(savePath, FileMode.OpenOrCreate, FileAccess.Write);
            NetworkStream stream = new NetworkStream(s);
            //定义缓冲区
            byte[] bb = new byte[1024];
            //循环读socket流
            int tt = 0;
            //进度条
            processB.Visible = true;
            processB.BackColor = System.Drawing.SystemColors.Control;
            int stepoff;
            if (romeFilel[romeFilel.Length - 1] == 'K')
                stepoff = 1024;
            else
                stepoff = 1024 * 1024;
            int totalste = int.Parse(romeFilel.Substring(0, romeFilel.Length - 1));
            progressBar2.Maximum = totalste;
            progressBar2.Step = totalste / 20;
            float recbytes = 0;
            while ((tt = stream.Read(bb, 0, 1024)) != 0)
            {//接收数据
                filestream.Write(bb, 0, tt);
                filestream.Flush();
                //更新进度条
                recbytes += (float)tt / stepoff;
                progressBar2.Value = (int)recbytes;
            }
            filestream.Close();
            processB.Visible = false;
            MessageBox.Show("文件接收完毕!");
        }
        //传送文件的线程————————功能:发送文件服务端
        public void sendFile()
        {
            TcpClient serverClient = new TcpClient();
            serverClient.Connect(romeIP, 2626);
            NetworkStream stream = serverClient.GetStream();
            //定义缓冲区
            byte[] bb = new byte[1024];
            //循环读文件
            int number;
            //进度条
            processA.Visible = true;
            processA.BackColor = System.Drawing.SystemColors.Window;
            int stepoff;
            if (romeFilel[romeFilel.Length - 1] == 'K')
                stepoff = 1024;
            else
                stepoff = 1024 * 1024;
            int totalste = int.Parse(romeFilel.Substring(0, romeFilel.Length - 1));
            progressBar1.Maximum = totalste;
            progressBar1.Step = totalste / 20;
            float sendedbytes = 0;
            while ((number = sendfilestream.Read(bb, 0, 1024)) != 0)
            {//向客户端发送流
                stream.Write(bb, 0, number);
                //刷新流
                stream.Flush();
                //进度条
                sendedbytes += (float)number / stepoff;
                progressBar1.Value = (int)sendedbytes;
            }
            sendfilestream.Close();
            stream.Close();
            processA.Visible = false;
            MessageBox.Show("文件传送完毕!");
        }
    }
}


说明:
     本程序通讯原理是局域网广播,如果使用组播技术可以实现跨网段通讯。传送文件使用p2p方式。


转载请注明本文地址: 局域网QQ第三版(V1.4)
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/zhengxiuchen86/article/details/81260921

智能推荐

c# 调用c++ lib静态库_c#调用lib-程序员宅基地

文章浏览阅读2w次,点赞7次,收藏51次。四个步骤1.创建C++ Win32项目动态库dll 2.在Win32项目动态库中添加 外部依赖项 lib头文件和lib库3.导出C接口4.c#调用c++动态库开始你的表演...①创建一个空白的解决方案,在解决方案中添加 Visual C++ , Win32 项目空白解决方案的创建:添加Visual C++ , Win32 项目这......_c#调用lib

deepin/ubuntu安装苹方字体-程序员宅基地

文章浏览阅读4.6k次。苹方字体是苹果系统上的黑体,挺好看的。注重颜值的网站都会使用,例如知乎:font-family: -apple-system, BlinkMacSystemFont, Helvetica Neue, PingFang SC, Microsoft YaHei, Source Han Sans SC, Noto Sans CJK SC, W..._ubuntu pingfang

html表单常见操作汇总_html表单的处理程序有那些-程序员宅基地

文章浏览阅读159次。表单表单概述表单标签表单域按钮控件demo表单标签表单标签基本语法结构<form action="处理数据程序的url地址“ method=”get|post“ name="表单名称”></form><!--action,当提交表单时,向何处发送表单中的数据,地址可以是相对地址也可以是绝对地址--><!--method将表单中的数据传送给服务器处理,get方式直接显示在url地址中,数据可以被缓存,且长度有限制;而post方式数据隐藏传输,_html表单的处理程序有那些

PHP设置谷歌验证器(Google Authenticator)实现操作二步验证_php otp 验证器-程序员宅基地

文章浏览阅读1.2k次。使用说明:开启Google的登陆二步验证(即Google Authenticator服务)后用户登陆时需要输入额外由手机客户端生成的一次性密码。实现Google Authenticator功能需要服务器端和客户端的支持。服务器端负责密钥的生成、验证一次性密码是否正确。客户端记录密钥后生成一次性密码。下载谷歌验证类库文件放到项目合适位置(我这边放在项目Vender下面)https://github.com/PHPGangsta/GoogleAuthenticatorPHP代码示例://引入谷_php otp 验证器

【Python】matplotlib.plot画图横坐标混乱及间隔处理_matplotlib更改横轴间距-程序员宅基地

文章浏览阅读4.3k次,点赞5次,收藏11次。matplotlib.plot画图横坐标混乱及间隔处理_matplotlib更改横轴间距

docker — 容器存储_docker 保存容器-程序员宅基地

文章浏览阅读2.2k次。①Storage driver 处理各镜像层及容器层的处理细节,实现了多层数据的堆叠,为用户 提供了多层数据合并后的统一视图②所有 Storage driver 都使用可堆叠图像层和写时复制(CoW)策略③docker info 命令可查看当系统上的 storage driver主要用于测试目的,不建议用于生成环境。_docker 保存容器

随便推点

网络拓扑结构_网络拓扑csdn-程序员宅基地

文章浏览阅读834次,点赞27次,收藏13次。网络拓扑结构是指计算机网络中各组件(如计算机、服务器、打印机、路由器、交换机等设备)及其连接线路在物理布局或逻辑构型上的排列形式。这种布局不仅描述了设备间的实际物理连接方式,也决定了数据在网络中流动的路径和方式。不同的网络拓扑结构影响着网络的性能、可靠性、可扩展性及管理维护的难易程度。_网络拓扑csdn

JS重写Date函数,兼容IOS系统_date.prototype 将所有 ios-程序员宅基地

文章浏览阅读1.8k次,点赞5次,收藏8次。IOS系统Date的坑要创建一个指定时间的new Date对象时,通常的做法是:new Date("2020-09-21 11:11:00")这行代码在 PC 端和安卓端都是正常的,而在 iOS 端则会提示 Invalid Date 无效日期。在IOS年月日中间的横岗许换成斜杠,也就是new Date("2020/09/21 11:11:00")通常为了兼容IOS的这个坑,需要做一些额外的特殊处理,笔者在开发的时候经常会忘了兼容IOS系统。所以就想试着重写Date函数,一劳永逸,避免每次ne_date.prototype 将所有 ios

如何将EXCEL表导入plsql数据库中-程序员宅基地

文章浏览阅读5.3k次。方法一:用PLSQL Developer工具。 1 在PLSQL Developer的sql window里输入select * from test for update; 2 按F8执行 3 打开锁, 再按一下加号. 鼠标点到第一列的列头,使全列成选中状态,然后粘贴,最后commit提交即可。(前提..._excel导入pl/sql

Git常用命令速查手册-程序员宅基地

文章浏览阅读83次。Git常用命令速查手册1、初始化仓库git init2、将文件添加到仓库git add 文件名 # 将工作区的某个文件添加到暂存区 git add -u # 添加所有被tracked文件中被修改或删除的文件信息到暂存区,不处理untracked的文件git add -A # 添加所有被tracked文件中被修改或删除的文件信息到暂存区,包括untracked的文件...

分享119个ASP.NET源码总有一个是你想要的_千博二手车源码v2023 build 1120-程序员宅基地

文章浏览阅读202次。分享119个ASP.NET源码总有一个是你想要的_千博二手车源码v2023 build 1120

【C++缺省函数】 空类默认产生的6个类成员函数_空类默认产生哪些类成员函数-程序员宅基地

文章浏览阅读1.8k次。版权声明:转载请注明出处 http://blog.csdn.net/irean_lau。目录(?)[+]1、缺省构造函数。2、缺省拷贝构造函数。3、 缺省析构函数。4、缺省赋值运算符。5、缺省取址运算符。6、 缺省取址运算符 const。[cpp] view plain copy_空类默认产生哪些类成员函数

推荐文章

热门文章

相关标签