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();
            }
        }

     
  • 相关阅读:
    原型模式(Prototype Pattern) 资料合集
    建筑者 & 生成器模式 (Builder Pattern) 资料合集
    CodeProject每日精选: Dialogs and Windows
    CodeProject每日精选: Edit Controls (TextBox, RichTextBox)
    抽象工厂资料汇总
    CodeProject每日精选 Winform Combo and Listboxes
    CodeProject每日精选: Date/Time controls 控件推荐
    Winform按钮推荐 2007.3.8
    hdu 2200
    hdu 1143总结
  • 原文地址:https://www.cnblogs.com/StevenChancxy/p/9213920.html
Copyright © 2011-2022 走看看