zoukankan      html  css  js  c++  java
  • Tcp和UDP的实现

     using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net 

    ;
    using System.Net 

    .Sockets;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;

    namespace _023_socket编程_UDP协议_服务器端
    {
        class Program
        {
            private static Socket udpServer;
            static void Main(string[] args)
            {
                //1,创建socket
                udpServer = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                //2,绑定ip跟端口号
                udpServer.Bind(new IPEndPoint(IPAddress.Parse("192.168.23.1 

    "), 8888));

                //3,接收数据
                new Thread(ReceiveMessage) { IsBackground = true }.Start();

                //udpServer.Close();
                Console.ReadKey();
            }

            static void ReceiveMessage()
            {
                while (true)
                {
                    EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
                    byte[] data = new byte[1024];
                    int length = udpServer.ReceiveFrom(data, ref remoteEndPoint);//这个方法会把数据的来源(ip:port)放到第二个参数上
                    string message = Encoding.UTF8.GetString(data, 0, length);
                    Console.WriteLine("从ip:" + (remoteEndPoint as IPEndPoint).Address.ToString() + ":" + (remoteEndPoint as IPEndPoint).Port + "收到了数据:" + message);
                }

            }
        }
    }
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net 

    ;
    using System.Net 

    .Sockets;
    using System.Text;
    using System.Threading.Tasks;

    namespace _025_udpclient
    {
        class Program
        {
            static void Main(string[] args)
            {
                //创建udpclient 绑定ip跟端口号
                Socket udpClient = new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);


                while (true)
                {
                    EndPoint serverPoint = new IPEndPoint(IPAddress.Parse("192.168.23.1 

    "),8888);
                    string message = Console.ReadLine();
                    byte[] data = Encoding.UTF8.GetBytes(message);
                    udpClient.SendTo(data,serverPoint);
                }


                udpClient.Close();
                Console.ReadKey();
            }
        }

     
  • 相关阅读:
    决定你人生高度的,不是你的才能,而是你的态度
    享受六一的最后几分钟
    DB9 公头母头引脚定义及连接
    bzoj3207--Hash+主席树
    bzoj1901 [ Zju2112 ] --树状数组套主席树
    bzoj1723 [ Usaco2009 Feb ] --前缀和(水题)
    bzoj3932 [ CQOI2015 ] --可持久化线段树
    bzoj3037--贪心
    bzoj3388 [ Usaco2004 Dec ] (神奇的解法)
    bzoj2693--莫比乌斯反演+积性函数线性筛
  • 原文地址:https://www.cnblogs.com/StevenChancxy/p/9213920.html
Copyright © 2011-2022 走看看