惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

酷 壳 – CoolShell
酷 壳 – CoolShell
H
Hacker News: Front Page
P
Palo Alto Networks Blog
T
ThreatConnect
Apple Machine Learning Research
Apple Machine Learning Research
博客园_首页
T
True Tiger Recordings
P
Privacy & Cybersecurity Law Blog
B
Blog
IT之家
IT之家
Last Week in AI
Last Week in AI
F
Full Disclosure
Hacker News: Ask HN
Hacker News: Ask HN
C
Comments on: Blog
Microsoft Azure Blog
Microsoft Azure Blog
C
Cybersecurity and Infrastructure Security Agency CISA
Microsoft Security Blog
Microsoft Security Blog
博客园 - 【当耐特】
N
News and Events Feed by Topic
NISL@THU
NISL@THU
腾讯CDC
雷峰网
雷峰网
Security Latest
Security Latest
李成银的技术随笔
M
Microsoft Research Blog - Microsoft Research
L
LangChain Blog
L
Lohrmann on Cybersecurity
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
C
Check Point Blog
Y
Y Combinator Blog
Recent Announcements
Recent Announcements
博客园 - Franky
N
News | PayPal Newsroom
V
V2EX
A
About on SuperTechFans
The Register - Security
The Register - Security
月光博客
月光博客
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Google Online Security Blog
Google Online Security Blog
MyScale Blog
MyScale Blog
Cisco Talos Blog
Cisco Talos Blog
Vercel News
Vercel News
WordPress大学
WordPress大学
C
Cyber Attacks, Cyber Crime and Cyber Security
The Hacker News
The Hacker News
IntelliJ IDEA : IntelliJ IDEA – the Leading IDE for Professional Development in Java and Kotlin | The JetBrains Blog
IntelliJ IDEA : IntelliJ IDEA – the Leading IDE for Professional Development in Java and Kotlin | The JetBrains Blog
爱范儿
爱范儿
A
Arctic Wolf
L
LINUX DO - 最新话题
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More

博客园 - 杞人

float、double为0判断 - 杞人 Excel操作知识(持续补充) 算法设计方案 C# 动态编译及反射执行 解决由于DTD规范引发Table设置高度无效 - 杞人 - 博客园 VS.NET 代码折叠Region C#访问FTP VS.NET 自动生成版本号问题 - 杞人 DataSet中表的关系及约束 - 杞人 Web Services 获取当前路径! - 杞人 Windows Services .NET超时解决方案 Facade 外观模式(结构型模式) Decorator 装饰模式(结构型模式) AJAX.NET请求时发生异常处理方案 setTimeout和setInterval的使用说明 write( ) 和 writeln( )使用说明 Composite 组合模式(结构型模式)
UDP通讯
杞人 · 2009-05-04 · via 博客园 - 杞人

Send  Receive方式

概述

为了和某一个远程主机通讯,在创建套接字后,使用Connect方法先和远程主机建立连接,然后直接用Send方法和Receive方法发送和接收数据。

发送端示例

using System;
using System.Collections.Generic;
using System.Text;

using System.Net;
using System.Net.Sockets;

namespace SendExamples
{
    /// <summary>
    /// 发送数据
    /// </summary>
    class Program
    {
        static void Main(string[] args)
        {
            string HostIP = System.Configuration.ConfigurationManager.AppSettings["HostIP"];
            int Port = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["Port"]);

            byte[] bytes = new byte[32768];
            string str = string.Empty;

                         Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            //定义远程终端IP地址和端口(实际使用时应为远程主机IP地址),为发送数据做准备
            IPEndPoint remote = new IPEndPoint(IPAddress.Parse(HostIP), Port);
            //建立与远程主机的连接
            socket.Connect(remote);

            while (true)
            {
                Console.Write("输入发送的信息(bye退出):");
                str = Console.ReadLine();
                //字符串转换为字节数组
                bytes = System.Text.Encoding.Unicode.GetBytes(str);
                //向远程终端发送信息
                socket.Send(bytes);

                if (str == "bye") break;
            }

            socket.Close();
        }
    }
}

接收端示例

using System;
using System.Collections.Generic;
using System.Text;

using System.Net;
using System.Net.Sockets;

namespace SendExamples
{
    /// <summary>
    /// 接收数据
    /// </summary>
    class Program
    {
        static void Main(string[] args)
        {
            int Port = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["Port"]);

            int length;
            byte[] bytes = new byte[32768];
            string str = string.Empty;

            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            //参数1指定本机IP地址(此处指所有可用的IP地址),参数2指定接收用的端口
            IPEndPoint myHost = new IPEndPoint(IPAddress.Any, Port);
            //将本机IP地址和端口与套接字绑定,为接收做准备
            socket.Bind(myHost);

            while (true)
            {
                Console.WriteLine("等待接收...");
                //从本地绑定的IP地址和端口接收远程终端的数据,返回接收的字节数
                length = socket.Receive(bytes);
                //字节数组转换为字符串
                str = System.Text.Encoding.Unicode.GetString(bytes, 0, length);
                if (str == "bye") break;
                Console.WriteLine("接收到信息:{0}", str);
            }

            socket.Close();
        }
    }
}

SendTo  ReceiveFrom方式

概述

SendTo和ReceiveFrom方法传送数据时,需要在参数中指定远程主机,这种方法适用于向多个远程主机发送数据的场合。比如动态生成远程主机的IP地址,达到向不同主机发送相同数据的目的。

发送端示例

 using System;
using System.Collections.Generic;
using System.Text;

using System.Net;
using System.Net.Sockets;

namespace SendToExamples
{
    /// <summary>
    /// 发送数据
    /// </summary>
    class Program
    {
        static void Main(string[] args)
        {
            string HostIP = System.Configuration.ConfigurationManager.AppSettings["HostIP"];
            int Port = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["Port"]);

            string str = string.Empty;
            byte[] bytes = new byte[32768];
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

            //定义远程IP地址和端口(实际使用时就为远程主机IP地址,为发送数据做准备
            IPEndPoint remote = new IPEndPoint(IPAddress.Parse(HostIP), Port);
            //从IPEndPoint得到EndPoint类型
            EndPoint remoteHost = (EndPoint)remote;


            while (true)
            {
                Console.Write("输入发送的信息:(bye退出)");
                str = Console.ReadLine();
                bytes = System.Text.Encoding.Unicode.GetBytes(str);
                socket.SendTo(bytes, remoteHost);
                if (str == "bye") break;
            }

            socket.Close();
        }
    }
}

接收端示例

 using System;
using System.Collections.Generic;
using System.Text;

using System.Net;
using System.Net.Sockets;

namespace ReceiveFromExamples
{
    /// <summary>
    /// 接收数据
    /// </summary>
    class Program
    {
        static void Main(string[] args)
        {
            int Port = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["Port"]);

            string str = string.Empty;
            int length;
            byte[] bytes = new byte[32768];
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

            //参数1指定本机IP地址(此处指所有可用的IP地址),参数2指定接收用的端口
            IPEndPoint myHost = new IPEndPoint(IPAddress.Any, Port);
            //将本机IP地址和端口与套接字绑定,为接收做准备
            socket.Bind(myHost);
            //从IPEndPoint得到EndPoint类型
            EndPoint remoteHost = (EndPoint)myHost;

            while (true)
            {
                Console.WriteLine("等待接收...");
                //从本地绑定的IP地址和端口接收远程终端的数据,返回接收的字节数
                length = socket.ReceiveFrom(bytes, ref remoteHost);
                //字节数组转换为字符串
                str = System.Text.Encoding.Unicode.GetString(bytes, 0, length);
                if (str == "bye") break;
                Console.WriteLine("接收到信息:{0}", str);
            }

            socket.Close();
        }
    }
}