zoukankan      html  css  js  c++  java
  • UDP Sockets in C#

    UDP provides an end-to-end service different from that of TCP.

    In fact, UDP performs only two functions:

    (1) it adds another layer of addressing (ports) to that of IP

    (2) it detects data corruption that may occur in transit and discards any corrupted messages

    Diffenence from TCP Sockets:

    1. UDP sockets do not have to be connected before being used.

    2. TCP is like telephone, and UDP is like email.

    UDP Client

    The typical UDP client goes through three steps:

    1. Construct an instance of UdpClient, optionally specifying the local address and port.
    2. Communicate by sending and receiving datagrams (byte arrays) using the Send() and
      Receive() methods of UdpClient.
    3. When finished, deallocate the socket using the Close() method of UdpClient.

    UdpEchoClient.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using Zeus.Thunder.Core;
    using System.Net; // For IPEndPoint
    using System.Net.Sockets; // For UdpClient, SocketException
    
    namespace SharpTrainer.NetWork
    {
        class UdpEchoClient : ITestCase
        {
            public void Run()
            {
                Console.Write("Input Server IP: ");
                string server = Console.ReadLine();
    
                Console.Write("Input Server Port: ");
                int servPort = Int32.Parse(Console.ReadLine());
    
                Console.Write("Input Echo String: ");
                byte[] sendPacket = Encoding.ASCII.GetBytes(Console.ReadLine());
    
                // Create a UdpClient instance
                UdpClient client = new UdpClient();
                try 
                {
                    // Send the echo string to the specified host and port
                    client.Send(sendPacket, sendPacket.Length, server, servPort);
                    Console.WriteLine("Sent {0} bytes to the server...", sendPacket.Length);
    
                    // This IPEndPoint instance will be populated with the remote sender’s
                    // endpoint information after the Receive() call
                    IPEndPoint remoteIPEndPoint = new IPEndPoint(IPAddress.Any, 0);
    
                    // Attempt echo reply receive
                    byte[] rcvPacket = client.Receive(ref remoteIPEndPoint);
    
                    Console.WriteLine("Received {0} bytes from {1}: {2}", rcvPacket.Length, remoteIPEndPoint,
                        Encoding.ASCII.GetString(rcvPacket, 0, rcvPacket.Length));
                } 
                catch (SocketException se) 
                {
                    Console.WriteLine(se.ErrorCode + ": " + se.Message);
                }
    
                client.Close();
            }
        }
    }

    UdpEchoServer.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using Zeus.Thunder.Core;
    using System.Net; // For IPEndPoint
    using System.Net.Sockets; // For UdpClient, SocketException
    
    namespace SharpTrainer.NetWork
    {
        class UdpEchoServer : ITestCase
        {
            public void Run()
            {
                Console.Write("Input Server Port: ");
                int servPort = Int32.Parse(Console.ReadLine());
    
                UdpClient client = null;
                 try {
                    // Create an instance of UdpClient on the port to listen on
                    client = new UdpClient(servPort);
                } catch (SocketException se) {
                    Console.WriteLine(se.ErrorCode + ": " + se.Message);
                    Environment.Exit(se.ErrorCode);
                }
    
                // Create an IPEndPoint instance that will be passed as a reference
                // to the Receive() call and be populated with the remote client info
                IPEndPoint remoteIPEndPoint = new IPEndPoint(IPAddress.Any, 0);
    
                for (;;) 
                { 
                    // Run forever, receiving and echoing datagrams
                    try {
                        // Receive a byte array with echo datagram packet contents
                        byte[] byteBuffer = client.Receive(ref remoteIPEndPoint);
                        Console.Write("Handling client at " + remoteIPEndPoint + " - ");
                        // Send an echo packet back to the client
                        client.Send(byteBuffer, byteBuffer.Length, remoteIPEndPoint);
                        Console.WriteLine("echoed {0} bytes.", byteBuffer.Length);
                    } catch (SocketException se) {
                        Console.WriteLine(se.ErrorCode + ": " + se.Message);
                    }
                }
            }
        }
    }

    运行结果:

    Server端:

    Handling client at 127.0.0.1:65005 - echoed 18 bytes.

    Client端:

    Input Server IP: 127.0.0.1
    Input Server Port: 9999
    Input Echo String: Hello Master HaKu!
    Sent 18 bytes to the server...
    Received 18 bytes from 127.0.0.1:9999: Hello Master HaKu!

  • 相关阅读:
    MySQL binlog中 format_desc event格式解析
    位bit和字节Byte
    MySQL利用mysqlbinlog模拟增量恢复
    mysqldump参数 --master-data详解
    开启MySQL二进制日志
    设置花里胡哨的Xshell字体与背景颜色(超全)
    Python操作MySQL数据库
    给定一个由括号([{)]}其中之一或多个组成的字符串判断是否符合左右括号成对标准,不同括号可任意嵌套
    给定一个字符串str,将str中连续两个字符为a的字符替换为b(一个或连续超过多个字符a则不替换)
    不使用局部变量和for循环或其它循环打印出如m=19,n=2結果为2 4 8 16 16 8 4 2形式的串
  • 原文地址:https://www.cnblogs.com/davidgu/p/4846624.html
Copyright © 2011-2022 走看看