TCP/IP网络通信-数据传输

时间:2022-05-02 16:08:34

1.通过网络IP实现数据的传输。

2.服务器端代码  【 服务端主要通过Socket类来创建一个监听等待客户端连接,服务端发送用send方法,接收用Receive方法】

using System.Net.Sockets;
using System.IO;
using System.Net;

 private void Waek_Load(object sender, EventArgs e)
        {
            //打开Listener开始监听  
            Thread thrListener = new Thread(new ThreadStart(Listen));
            thrListener.Start();  
        }
        //监听数据  
        private static Encoding encode = Encoding.Default;
        private void Listen()
        {
            Socket listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            listenSocket.Bind(new IPEndPoint(IPAddress.Any, 10000));//获取服务器IP,和设置一个端口号
            listenSocket.Listen(100);
            Socket acceptSocket = listenSocket.Accept();//一直等待,直到有客户端连入
            while (true)//客户端连入才会到循环。
            {
                try
                {
                    string receiveData = Receive(acceptSocket, 5000); //5 seconds timeout.
                    if (receiveData != "")
                    {
                       //接收客户端发送的数据
                        Invoke((EventHandler)delegate { label5.Text = receiveData; });
                        //给客户端回复数据
                        acceptSocket.Send(encode.GetBytes("ok+00 00 01 02 03"));
                    }
                }
                catch (Exception ex) { 
                }
                
            }
        }
        /// <summary>
        /// 接收数据
        /// </summary>
        /// <param name="socket"></param>
        /// <param name="timeout"></param>
        /// <returns></returns>
        private static string Receive(Socket socket, int timeout)
        {
            string result = string.Empty;
            socket.ReceiveTimeout = timeout;
            List<byte> data = new List<byte>();
            byte[] buffer = new byte[1024];
            int length = 0;
            try
            {
                while ((length = socket.Receive(buffer)) > 0)
                {
                    for (int j = 0; j < length; j++)
                    {
                        data.Add(buffer[j]);
                    }
                    if (length < buffer.Length)
                    {
                        break;
                    }
                }
            }
            catch { }
            if (data.Count > 0)
            {
                result = encode.GetString(data.ToArray(), 0, data.Count);
            }
            return result;
        }
        /// <summary>
        /// 销毁Socket对象
        /// </summary>
        /// <param name="socket"></param>
        private static void DestroySocket(Socket socket)
        {
            if (socket.Connected)
            {
                socket.Shutdown(SocketShutdown.Both);
            }
            socket.Close();
        }
 

3.客户端代码【客户端端主要通过TcpClient类去连接服务端 将连接好的对象赋值给NetworkStream类来发送和接收数据 接收用Read()方法,发送用Wirte()方法】

        NetworkStream ntwStream = null;
        TcpClient tcpClient = null;
        private void Form1_Load(object sender, EventArgs e)
        {
            tcpClient = new TcpClient();
            tcpClient.Connect(System.Net.IPAddress.Parse("172.17.100.97"), 10000);//设置链接到的服务器地址及端口
            ntwStream = tcpClient.GetStream();//开始链接
            // 打印连接到的服务端信息
            label1.Text = string.Format("已经成功与客户端建立连接!{0} --> {1}", tcpClient.Client.LocalEndPoint, tcpClient.Client.RemoteEndPoint);
           //启动接收服务器发送来的数据
            Thread thrListener = new Thread(new ThreadStart(Listen));
            thrListener.Start();
        }
        //监听数据  
        private static Encoding encode = Encoding.Default;
        private void Listen()
        {
            while (true)
            {
                try
                {
                    byte[] buffer = new byte[1024];
                    int receiveData = ntwStream.Read(buffer, 0, buffer.Length);
                    int length = 0;
                    if (receiveData != 0)
                    {
                        List<byte> data = new List<byte>();
                        length = buffer.Length;
                        for (int j = 0; j < length; j++)
                        {
                            data.Add(buffer[j]);
                        }
                        string result = encode.GetString(data.ToArray(), 0, data.Count);
                        Invoke((EventHandler)delegate { textBox2.Text = result.ToString(); });
                    }
                }
                catch (Exception ex)
                {
                }

            }
        }

  

//客户端往服务器写入数据
private void button1_Click(object sender, EventArgs e)
        {
            if (ntwStream.CanWrite)
            {
                Byte[] bytSend = Encoding.UTF8.GetBytes(textBox1.Text);
                ntwStream.Write(bytSend, 0, bytSend.Length);
            }
            else
            {
                Console.WriteLine("无法写入数据流");
                ntwStream.Close();
                tcpClient.Close();
                return;
            }
        }

  //截图

TCP/IP网络通信-数据传输

TCP/IP网络通信-数据传输