c# 网络编程知识整理(一)

今天学习了c#网络编程的一些东西,在这里记下来。

1、客户端连接远程服务器

     TcpClient client = new TcpClient();
     client.Connect(IPAddress.Parse("192.168.0.123"), 8500);

2、服务端打开端口等待客户端连接   

     IPAddress ip = new IPAddress(new byte[] { 192, 168, 0, 123 });
      TcpListener listener = new TcpListener(ip, 8500);
      listener.Start();
      Console.WriteLine("Start Listenning ...");
      while (true)
      {
         TcpClient client = listener.AcceptTcpClient();
      }

3、发送消息

     byte[] temp = Encoding.Unicode.GetBytes(msg);

     NetworkStream streamToServer.Write(temp, 0, temp.Length);

     同步接收消息

     int byteRead = streamToClient.Read(buffer, 0, 8192);

     string msg = Encoding.Unicode.GetString(buffer, 0, byteRead);

     异步接收消息

     AsyncCallback callBack = new AsyncCallback(ReadComplete);
      streamToServer.BeginRead(buffer, 0, BufferSize, callBack, null);

      ReadComplete(IAsyncResult ar)是回调函数,当异步接收执行完成以后,会自动调用回调函数。   

        private void ReadComplete(IAsyncResult ar)
        {
            int bytesRead;
            try
            {
                lock (streamToServer)
                {
                    bytesRead = streamToServer.EndRead(ar);
                }
                if (bytesRead == 0)
                {
                    throw new Exception("读取到0字节");
                }
                string msg = Encoding.Unicode.GetString(buffer, 0, bytesRead);
                Console.WriteLine("Received: {0}",msg);
                Array.Clear(buffer, 0, buffer.Length);
                lock (streamToServer)
                {
                    AsyncCallback callBack = new AsyncCallback(ReadComplete);
                    streamToServer.BeginRead(buffer, 0, BufferSize, callBack, null);
                }
            }
            catch(Exception ex)
            {
                if (streamToServer != null)
                {
                    streamToServer.Dispose();
                    client.Close();
                    Console.WriteLine(ex.Message);
                    return;
                }
            }
        }   

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值