• TCP Client 及 Server 示例


    Client 端 Code:

    public class TcpTimeClient
    {
        private const int portNum = 13;
        private const string hostName = "LocalHost";

        public static int Main(String[] args)
        {
            try
            {
                TcpClient client = new TcpClient(hostName, portNum);

                NetworkStream ns = client.GetStream();

                byte[] bytes = new byte[1024];
                int bytesRead = ns.Read(bytes, 0, bytes.Length);

                Console.WriteLine(Encoding.ASCII.GetString(bytes, 0, bytesRead));

                Console.ReadKey();
                client.Close();

            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
           
            return 0;
        }
    }

    Server 端 Code:

    public class TcpTimeServer
    {

        private const int portNum = 13;

        public static int Main(String[] args)
        {
            bool done = false;

            TcpListener listener = new TcpListener(portNum);

            listener.Start();

            while (!done)
            {
                Console.Write("Waiting for connection...");
                TcpClient client = listener.AcceptTcpClient(); // 等待客户端连接

                Console.WriteLine("Connection accepted.");
                NetworkStream ns = client.GetStream();

                byte[] byteTime = Encoding.ASCII.GetBytes(DateTime.Now.ToString());

                try
                {
                    ns.Write(byteTime, 0, byteTime.Length);
                    ns.Close();
                    client.Close();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                }
            }

            listener.Stop();

            return 0;
        }

    }

    ~做事情贵在坚持~
  • 相关阅读:
    使用Fiddler抓包(手机端app)
    IE浏览器跳转url正常,谷歌浏览器跳转报403状态
    书签
    工作记录
    MySQL索引、锁和优化
    Pytorch-张量的创建与使用方法
    网络请求
    数据挖掘的五大流程
    uni开启下拉刷新
    uni-app中的tabBar配置
  • 原文地址:https://www.cnblogs.com/csMapx/p/2072694.html
Copyright © 2020-2023  润新知