Материал из .Net Framework эксперт
new UdpClient(eceive
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
class MainClass {
private static void Main() {
IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8888);
Thread receiveThread = new Thread(ReceiveData);
receiveThread.IsBackground = true;
receiveThread.Start();
UdpClient client = new UdpClient();
try {
string text = "message";
byte[] data = Encoding.UTF8.GetBytes(text);
client.Send(data, data.Length, remoteEndPoint);
} catch (Exception err) {
Console.WriteLine(err.ToString());
} finally {
client.Close();
}
}
private static void ReceiveData() {
UdpClient client = new UdpClient(5555);
while (true) {
try {
IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, 0);
byte[] data = client.Receive(ref anyIP);
string text = Encoding.UTF8.GetString(data);
Console.WriteLine(">> " + text);
} catch (Exception err) {
Console.WriteLine(err.ToString());
}
}
}
}
UDP multi-cast
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.IO.rupression;
using System.Net;
using System.Net.Mail;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Xml;
public class MainClass
{
public static void Main()
{
using (UdpClient udp = new UdpClient(1024))
{
IPAddress groupAddress = IPAddress.Parse("0.0.0.0");
udp.JoinMulticastGroup(groupAddress, 32);
udp.EnableBroadcast = true;
IPEndPoint sentBy = null;
byte[] data = udp.Receive(ref sentBy);
udp.DropMulticastGroup(groupAddress);
}
}
}
Udp time out option
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
class MainClass
{
public static void Main()
{
byte[] data = new byte[1024];
string input, stringData;
int receivedDataLength;
IPEndPoint ip = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9999);
Socket server = new Socket(AddressFamily.InterNetwork,SocketType.Dgram, ProtocolType.Udp);
int sockopt = (int)server.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout);
Console.WriteLine("Default timeout: {0}", sockopt);
server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 3000);
sockopt = (int)server.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout);
Console.WriteLine("New timeout: {0}", sockopt);
server.Close();
}
}