zoukankan      html  css  js  c++  java
  • [引]VS帮助文档的 socket连接的Listen和Connect 及 Tcp连接的TcpListener和TcpClient

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

    //socket listen
    private void btn_startlisten_Click(object sender, EventArgs e)
    {
        try
        {
            // create the socket
            Socket listenSocket = new Socket(AddressFamily.InterNetwork,
                                             SocketType.Stream,
                                             ProtocolType.Tcp);
            // bind the listening socket to the port           
            IPAddress hostIP = IPAddress.Parse("127.0.0.1");
            int port = 4567;
            //IPAddress hostIP = (Dns.Resolve(IPAddress.Any.ToString())).AddressList[0];           
            IPEndPoint ep = new IPEndPoint(hostIP, port);
            listenSocket.Bind(ep);

            // start listening
            int backlog = 0;
            listenSocket.Listen(backlog);

            while (true)
            {
                if (listenSocket.Poll(-1, SelectMode.SelectRead))
                {
                    Socket mySocket = listenSocket.Accept();

                    byte[] bytes = new byte[256];
                    mySocket.Receive(bytes);
                    this.txt_Msg.Text += string.Format(Encoding.UTF8.GetString(bytes) + "\r\n");
                    //MessageBox.Show(Encoding.UTF8.GetString(bytes));

                    byte[] msg = Encoding.UTF8.GetBytes("This is a test S->C" + DateTime.Now.ToString());
                    mySocket.Send(msg);

                    mySocket.Shutdown(SocketShutdown.Both);
                    mySocket.Close();
                }
            }
            //listenSocket.Close();
        }
        catch (Exception ex)
        {
            this.txt_Msg.Text = ex.ToString();
        }
    }

    //socket client
    private void button1_Click(object sender, EventArgs e)
    {
        try
        {
            byte[] msg = Encoding.UTF8.GetBytes("This is a test C->S"+DateTime.Now.ToString());
            byte[] bytes = new byte[256];

            Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            s.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 4567));
            // Blocks until send returns.
            int i = s.Send(msg);
            this.textBox1.Text = string.Format("Sent {0} bytes.", i);

            // Get reply from the server.
            i = s.Receive(bytes);
            this.textBox1.Text = string.Format(Encoding.UTF8.GetString(bytes));

            //释放资源
            s.Close();
        }
        catch (Exception ex)
        {
            this.textBox1.Text = ex.ToString();
        }
    }

     

    //TcpListener
    private void button1_Click(object sender, EventArgs e)
            {
                TcpListener server = null;
                try
                {
                    // Set the TcpListener on port 13000.
                    Int32 port = 13000;
                    IPAddress localAddr = IPAddress.Parse("127.0.0.1");

                    // TcpListener server = new TcpListener(port);
                    server = new TcpListener(localAddr, port);

                    // Start listening for client requests.
                    server.Start();

                    // Buffer for reading data
                    Byte[] bytes = new Byte[256];
                    String data = null;
                   
                    int j = 0;//
                    // Enter the listening loop.
                    while (j<2)//true
                    {
                        j = j + 1;
                        // Perform a blocking call to accept requests.
                        // You could also user server.AcceptSocket() here.
                        TcpClient client = server.AcceptTcpClient();

                        data = null;

                        // Get a stream object for reading and writing
                        NetworkStream stream = client.GetStream();

                        int i;

                        // Loop to receive all the data sent by the client.
                        while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
                        {
                            // Translate data bytes to a ASCII string.
                            data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
                            this.textBox1.Text += DateTime.Now.ToString() + " Received: " + data+"\r\n";

                            // Process the data sent by the client.
                            data = data.ToUpper() + DateTime.Now.ToString();                     

                            byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);

                            // Send back a response.
                            stream.Write(msg, 0, msg.Length);
                            this.textBox1.Text += " Sent back: " + data + "\r\n";
                        }

                        // Shutdown and end connection
                        client.Close();
                    }
                   
                }
                catch (SocketException ex)
                {
                    this.textBox1.Text = ex.ToString();
                }
                finally
                {
                    // Stop listening for new clients.
                    server.Stop();
                }

            }

    //TcpClient
    private void button1_Click(object sender, EventArgs e)
    {
        try
        {
          
            // Create a TcpClient.
            // Note, for this client to work you need to have a TcpServer
            // connected to the same address as specified by the server, port
            // combination.
            string server = "127.0.0.1";
            Int32 port = 13000;
            TcpClient client = new TcpClient(server, port);

            string message = " test data c->s ";
            // Translate the passed message into ASCII and store it as a Byte array.
            Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);

            // Get a client stream for reading and writing.
            //  Stream stream = client.GetStream();

            NetworkStream stream = client.GetStream();

            // Send the message to the connected TcpServer.
            stream.Write(data, 0, data.Length);

            this.textBox1.Text += DateTime.Now.ToString() + "Sent:" + message + "\r\n";

            // Receive the TcpServer.response.

            // Buffer to store the response bytes.
            data = new Byte[256];

            // String to store the response ASCII representation.
            String responseData = String.Empty;

            // Read the first batch of the TcpServer response bytes.
            Int32 bytes = stream.Read(data, 0, data.Length);
            responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
            this.textBox1.Text += DateTime.Now.ToString() + "Received:" + responseData + "\r\n";
            // Close everything.
            stream.Close();
            client.Close();
        }
        catch (ArgumentNullException ex)
        {
            this.textBox1.Text = ex.ToString();
        }
        catch (SocketException ex)
        {
            this.textBox1.Text = ex.ToString();
        }
    }

  • 相关阅读:
    RHEL7 安装Docker-CE
    Django2.2 Vue 前后端分离 无法访问Cookie
    Vue error: Parsing error: Unexpected token
    Python Warning
    Http post 接收 html .netcore
    Echart 中国地图
    CKplayer 视频播放插件
    (转)解决windows10下无法安装.net framework 3.5,错误代码0x800F081F
    第1章 信息化和信息系统
    .net core 添加 swagger
  • 原文地址:https://www.cnblogs.com/freeliver54/p/1279360.html
Copyright © 2011-2022 走看看