zoukankan      html  css  js  c++  java
  • 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;
        }

    }

    ~做事情贵在坚持~
  • 相关阅读:
    C#根据url生成唯一的key
    MyBatis基本配置和实践(四)
    MyBatis基本配置和实践(三)
    MyBatis基本配置和实践(二)
    MyBatis基本配置和实践(一)
    dbcp2、c3p0、druid连接池的简单配置
    HTTP长连接和短连接
    Java Web高性能开发
    三层构架 和 MVC 是什么?
    Docker bridge探索
  • 原文地址:https://www.cnblogs.com/csMapx/p/2072694.html
Copyright © 2011-2022 走看看