WinForm:TCPServer接收Json数据并把数据显示到Listview里

TCPServer接收Json数据并把数据显示到Listview里。
一、创建服务端
在这里插入图片描述
代码如下:

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

namespace SoundWaveTCPserver
{
    public partial class Form1 : Form
    {

        Socket socket_TCP = null;

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //无填写提示填写
            if (String.IsNullOrEmpty(textBox1.Text) )
            {
                MessageBox.Show("请输入IP");
            }else if(String.IsNullOrEmpty(textBox2.Text))
            {
                MessageBox.Show("请输入Port");
            }

            socket_TCP = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket_TCP.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.ReuseAddress,true);//允许同一端口可以多开
            IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse(textBox1.Text),int.Parse(textBox2.Text));
            MainWindow mainWindow = new MainWindow(socket_TCP,ipEndPoint);//把socket传入到另外一个窗口
            mainWindow.ShowDialog();

        }


        /// <summary>
        /// 获取本机IP地址
        /// </summary>
        /// <returns></returns>
        public string GetLocalIp()
        {
            string AddressIP = string.Empty;
            foreach (IPAddress _IPAddress in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
            {
                if (_IPAddress.AddressFamily.ToString() == "InterNetwork")
                {
                    AddressIP = _IPAddress.ToString();
                }
            }
            return AddressIP;
        }
        /// <summary>
        /// 添加IP和Port到窗口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_Load(object sender, EventArgs e)
        {
            textBox1.Text = GetLocalIp();
            textBox2.Text = "5000";
        }
    }
}

二、第二个窗口负责显示信息

        Socket socket_TCP = null;
        IPEndPoint iPEndPoint = null;
        Thread thread_Listen = null;
        Socket socket_Communication = null;
        Dictionary<string, Socket> dic = new Dictionary<string, Socket>();
        ArrayList list = new ArrayList();//作为大集合
        ArrayList list1 = new ArrayList();//作为集合
        public MainWindow(Socket mysocket,IPEndPoint myipendpoint)
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
            this.socket_TCP = mysocket;
            this.iPEndPoint = myipendpoint;
            socket_TCP.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            socket_TCP.Bind(iPEndPoint);
            socket_TCP.Listen(0);
            thread_Listen = new Thread(TCP_Listen);
            thread_Listen.IsBackground = true;
            thread_Listen.Start();
        }
        
        private void TCP_Listen()
        {
            while (true)
            {
                try
                {
                    socket_Communication = socket_TCP.Accept();
                    string RemoteEndPoint = socket_Communication.RemoteEndPoint.ToString(); //客户端网络节点
                    dic.Add(RemoteEndPoint, socket_Communication);
                    System.Windows.Forms.ListViewItem EPCitem = new System.Windows.Forms.ListViewItem((listView1.Items.Count + 1).ToString());
                    EPCitem.SubItems.Add(RemoteEndPoint);
                    EPCitem.SubItems.Add(GetTimeStamp());
                    listView1.Items.Add(EPCitem);
                    ParameterizedThreadStart pts = new ParameterizedThreadStart(TCP_Read);
                    Thread thread = new Thread(pts);
                    thread.IsBackground = true;
                    thread.Start(socket_Communication);
                }
                catch (Exception ex)
                {
                    break;
                }
            }
        }
        private List<byte> buffer = new List<byte>();
        private void TCP_Read(object socket_Read)
        {                                                                                             
            Socket socket = socket_Read as Socket;
            while (true)
            {
                try
                {
                    Thread.Sleep(100);
                    byte[] buffer_data = new byte[1024*1024];
                    int Accept_length = socket.Receive(buffer_data);
                    EndPoint endPoint = socket.RemoteEndPoint;
                    string Str_Data = Encoding.Default.GetString(buffer_data,0,buffer_data.Length).Trim("\0".ToCharArray());


                    if (Str_Data.Substring(0, 2) == "aa" && Str_Data.Substring(Str_Data.Length - 2, 2) == "AA")
                    {
                        switch (Str_Data.Substring(2, 2))
                        {
                            case "00":
                                string str = null;
                                foreach (var item in dic)
                                {
                                    str += item.Key + " ";
                                }
                                TCP_Write(str, endPoint.ToString());
                                break;
                            case "01":
                                TCP_Write(Str_Data.Substring(19, Str_Data.Length - 21), Str_Data.Substring(4, 15));
                                break;
                            default:
                                break;
                        }
                    }
                    else
                    {
                        lock (buffer)
                        {


                            buffer.AddRange(buffer_data);
                            int index = 1;
                            int bracecount = 1;
                            int zeronum = 0;
                            while (buffer.Count >= 4)
                            {
                                if (buffer[0] == 0x7B)
                                {
                                    if (buffer[index] == 0x7B)
                                    {
                                        bracecount++;
                                    }
                                    if (buffer[index] != 0x7D)
                                    {
                                        index++;
                                        if (buffer[index] == 0x00)
                                        {
                                            zeronum++;
                                        }
                                        if (index >= buffer.Count || zeronum > 100)
                                        {
                                            zeronum = 0;
                                            break;
                                        }
                                    }
                                    else if (bracecount != 0)
                                    {
                                        bracecount--;
                                        if (bracecount == 0)
                                        {
                                            byte[] ReceiveBytes = new byte[index + 1];
                                            buffer.CopyTo(0, ReceiveBytes, 0, index + 1);
                                            string message = Encoding.UTF8.GetString(ReceiveBytes);
                                            datachuli(message, endPoint);
                                            buffer.RemoveRange(0, index + 1); //数据处理
                                            index = 1;
                                            bracecount = 1;
                                        }
                                        index++;
                                    }
                                }
                                else
                                {
                                    buffer.RemoveRange(0, 1);
                                }
                            }
                        }
                    }

                    
                }
                catch (Exception)
                {
                    try
                    {
                        dic.Remove(socket.RemoteEndPoint.ToString());
                        String s = socket.RemoteEndPoint.ToString();
                        int nRowOrder = listView1.Items.Count;
                        if(nRowOrder != 0)
                        {
                            for(int i =0;i < nRowOrder; i++)
                            {
                                string Ip = listView1.Items[i].SubItems[1].Text;

                                if(Ip == s)
                                {
                                    listView1.Items[i].Remove();
                                    list.RemoveAt(i);
                                }
                            }
                        }
                    }
                    catch(Exception)
                    {
                        socket_Communication.Close();
                        break;
                    }
                    socket_Communication.Close();
                    break ;
                }



            }
        }
        private void TCP_Write(string data, string EndPoint)
        {
            try
            {
                dic[EndPoint].Send(Encoding.UTF8.GetBytes(data));
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
                return;
            }
        }
 private void datachuli(string message, EndPoint endPoint)
        {
            System.Windows.Forms.ListViewItem EPCitem = new System.Windows.Forms.ListViewItem((listView2.Items.Count + 1).ToString());
            Root rt;
            try { 
                rt = JsonConvert.DeserializeObject<Root>(message);
                if (rt != null)
                {
                    
                    EPCitem.SubItems.Add(rt.Id);
                    EPCitem.SubItems.Add(rt.maxvalue.ToString());
                    EPCitem.SubItems.Add(rt.minvalue.ToString());
                    EPCitem.SubItems.Add(rt.Mean.ToString());
                    EPCitem.SubItems.Add(rt.Variance.ToString());
                    list1.Add(EPCitem);
                    int nRowOrder = listView1.Items.Count;
                    if (nRowOrder != 0)
                    {
                        //找到对应的ID序列号 
                        for(int j =0;j < nRowOrder;j++)
                        {
                            string Id = listView1.Items[j].SubItems[1].Text;
                            
                            if (Id == endPoint.ToString())
                            {
                                //找到就提取大集合中的数据到小集合中,删除大集合处的数据,利用小集合中的数据插入,删除小集合中的数据
                                if (list[j] != null)
                                {
                                    System.Windows.Forms.ListViewItem EPCitemlist = new System.Windows.Forms.ListViewItem((listView1.Items.Count + 1).ToString());
                                    var datalist = list[j];
                                    ArrayList data = (ArrayList)datalist;
                                    for(int i = 0;i < data.Count; i++)
                                    {
                                        var a = data[i];
                                        EPCitemlist = (System.Windows.Forms.ListViewItem)a;
                                        list1.Add(EPCitemlist);
                                    }
                                    list.RemoveAt(j);
                                    list.Insert(j, new ArrayList(list1));
                                    list1.Clear();

                                }
                                else //发现大集合下的序列号没有赋值,利用小集数据进行插入并清除,
                                {
                                    list.Insert(j,new ArrayList(list1));
                                    list1.Clear();
                                }
                            }
                        }
                    }
                }
            
            }
            catch(Exception) { }    

        }
        private void MainWindow_Load(object sender, EventArgs e)
        {
            //列表头创建
            listView1.Columns.Add("ID", 25, System.Windows.Forms.HorizontalAlignment.Center);
            listView1.Columns.Add("IP", 150, System.Windows.Forms.HorizontalAlignment.Center);
            listView1.Columns.Add("Time", 150, System.Windows.Forms.HorizontalAlignment.Center);
            listView1.GridLines = true;
            listView1.FullRowSelect = true;
            listView1.MultiSelect = false;
            listView2.Columns.Add("ID", 25, System.Windows.Forms.HorizontalAlignment.Center);
            listView2.Columns.Add("UID", 50, System.Windows.Forms.HorizontalAlignment.Center);
            listView2.Columns.Add("MaxValue", 60, System.Windows.Forms.HorizontalAlignment.Center);
            listView2.Columns.Add("MinValu", 60, System.Windows.Forms.HorizontalAlignment.Center);
            listView2.Columns.Add("Mean", 50, System.Windows.Forms.HorizontalAlignment.Center);
            listView2.Columns.Add("Variance", 75, System.Windows.Forms.HorizontalAlignment.Center);
            listView2.GridLines = true;
            listView2.FullRowSelect = true;
            listView2.MultiSelect = false;
            for(int i = 0; i < 255; i++)
            {
                list.Add(null);
            }
        }
        public string GetTimeStamp()
        {
            DateTime dt = DateTime.Now;
            //return dt.ToLongTimeString();
            return dt.ToString();
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值