c#实现基于Tcp协议的网络通讯

本文档展示了如何使用C#实现基于Tcp协议的网络通讯,包括客户端和服务器端的代码实现。客户端通过TcpClient连接到指定的服务器端口,读取并打印服务器发送的数据;服务器端通过TcpListener监听特定端口,接受连接并发送当前时间戳给客户端。
摘要由CSDN通过智能技术生成

一.先运行服务器端--客户端

二.客户端代码

 private const int portNum =13;//服务器端口
        private const string hostName = "127.0.0.1";
        [STAThread]
        static void Main(string[] args)
        {
            try
            {
                Console.Write("Try to connect to"+hostName+":"+portNum.ToString()+"\r\n");
                TcpClient client = new TcpClient(hostName, portNum);
                NetworkStream ns = client.GetStream();//获取数据流
                byte[] bytes = new byte[1024];//存放s从流中读取的数据
                //读取字节流
                int bytesRead = ns.Read(bytes, 0, bytes.Length);//bytes缓冲数组,0缓冲数组中存放的位置,Length读取的字节数据
                Console.WriteLine(Encoding.ASCII.GetString(bytes,0,bytesRead));
                client.Close();
               // Console.ReadLine();
            }
            catch (Exception e) 
            {
                Console.WriteLine(e.ToString());
            }
        }

三.服务器端代码

 private const int portNum =13;
        [STAThread]
        public static void Main(string[] args)
        {
            bool done = false;
            IPAddress MyIP = IPAddress.Parse("127.0.0.1");
            TcpListener listener = new TcpListener(MyIP,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(); 
        }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值