本文整理汇总了C#中System.Net.Sockets.UdpClient类的典型用法代码示例。如果您正苦于以下问题:C# UdpClient类的具体用法?C# UdpClient怎么用?C# UdpClient使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
UdpClient类属于System.Net.Sockets命名空间,在下文中一共展示了UdpClient类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: serverLoop
protected void serverLoop()
{
Trace.WriteLine("Waiting for UDP messages.");
listener = new UdpClient(UDP_PORT);
IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, UDP_PORT);
byte[] receive_byte_array;
bool running = true;
while (running)
{
try
{
receive_byte_array = listener.Receive(ref groupEP);
if (receive_byte_array.Length != 2)
{
Trace.WriteLine("Invalid UDP message received. Ignored message!");
continue;
}
Trace.WriteLine("Upp fan speed message received.");
int fan = receive_byte_array[0];
byte speed = receive_byte_array[1];
fanControlDataObject.setPinSpeed(fan, speed, true);
}
catch
{
running = false;
}
}
}
示例2: IPEndPoint
/*
// TODO: Асинхронная отправка! Или не нужно?
/// <summary>
/// Отправить единичное сообщение на единичный хост
/// </summary>
/// <param name="text">Текст сообщения</param>
// internal static void SendMessage(string RemoteHost, string text)
{
TcpClient client = null;
NetworkStream networkStream = null;
try
{
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, 12000);
// TODO : заменить 127.0.0.1 на что-то более верное
// TODO: добавить динамическое выделение портов (из пула свободных портов)
// получатель сообщения при
IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Parse(RemoteHost), 11000);
// TODO :забить номера портов в настройки
client = new TcpClient(localEndPoint);
client.Connect(remoteEndPoint);
networkStream = client.GetStream();
byte[] sendBytes = Encoding.UTF8.GetBytes(text);
networkStream.Write(sendBytes, 0, sendBytes.Length);
byte[] bytes = new byte[client.ReceiveBufferSize];
networkStream.Read(bytes, 0, client.ReceiveBufferSize);
string returnData = Encoding.UTF8.GetString(bytes);
//MessageBox.Show(returnData);
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
finally
{
if (networkStream != null) networkStream.Close();
if (client!=null) client.Close();
}
}
*/
// реализаця с UDP
internal static void SendMessage(string RemoteHost, string text)
{
UdpClient client = null;
try
{
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, 12000);
// получатель сообщения при
IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Parse(RemoteHost), 11000);
// TODO :забить номера портов в настройки
client = new UdpClient(localEndPoint);
byte[] sendBytes = Encoding.ASCII.GetBytes(text);
networkStream.Write(sendBytes, 0, sendBytes.Length);
byte[] bytes = new byte[client.ReceiveBufferSize];
networkStream.Read(bytes, 0, client.ReceiveBufferSize);
string returnData = Encoding.UTF8.GetString(bytes);
//MessageBox.Show(returnData);
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
finally
{
if (networkStream != null) networkStream.Close();
if (client != null) client.Close();
}
}
示例3: ServerContext
public ServerContext(int port, int maxclients, ref List<string> TextStack, string OwnIP)
{
BeginSendUdpServerCallback = new AsyncCallback(OnBeginSendUdpServerCallbackFinished);
ServerMessage = System.Text.Encoding.ASCII.GetBytes("OK:" + OwnIP);
UdpServer = new UdpClient(new IPEndPoint(IPAddress.Any, 8011)); //da bei xp fehler
UdpServer.JoinMulticastGroup(BroadcastServer.Address);
UdpServer.BeginSend(ServerMessage, ServerMessage.Length, BroadcastServer, BeginSendUdpServerCallback, null);
MaxClients = maxclients;
Ip = IPAddress.Any;
this.Port = port;
listener = new TcpListener(Ip, Port);
Clients = new List<ClientContext>(MaxClients);
listener.Start();
BeginAcceptSocketCallback = new AsyncCallback(OnClientConnected);
this.TextStack = TextStack;
}
示例4: Find
private void Find()
{
try
{
Cursor = Cursors.WaitCursor;
byte[] dnsQuery;
byte[] dnsReply;
UdpClient dnsClient = new UdpClient(textBoxDnsServer.Text, 53);
dnsQuery = MakeQuery(DateTime.Now.Millisecond * 60,
textBoxDomain.Text);
dnsClient.Send(dnsQuery, dnsQuery.Length);
IPEndPoint ipEndPoint = null;
dnsReply = dnsClient.Receive(ref ipEndPoint);
richTextBoxMXServers.Text = MakeResponse(dnsReply, textBoxDomain.Text);
}
catch (SocketException ex)
{
MessageBox.Show(ex.Message, "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
Cursor = Cursors.Default;
}
}
示例5: UdpClientAdapter
public UdpClientAdapter(UdpClient udpClient)
{
if (udpClient == null)
throw new ArgumentNullException("udpClient");
_udpClient = udpClient;
}
示例6: Connect
// Connect for receiving messages
public bool Connect(int localPort)
{
Disconnect();
receiveDone.Reset();
// Connect to a local port.
try
{
localEP = new IPEndPoint(IPAddress.Any, localPort);
// Create a UDP Client.
clientReceive = new System.Net.Sockets.UdpClient(localEP);
if (ConnectedStateChanged != null) ConnectedStateChanged(this, new ConnectedStateChangedEventArgs(true));
// Setup the receiver client thread
receiverTask = new Thread(ReceiverLoop);
receiverTask.Start();
// Signal that the connection has been made.
connectDone.Set();
}
catch (Exception e)
{
Disconnect();
//
Console.WriteLine(e.ToString());
}
return IsConnected;
}
示例7: Send
public override void Send(string serverHostName, string serverIpAddress, int serverPort, string message)
{
var ipAddress = IPAddress.Parse(serverIpAddress);
IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, serverPort);
using(UdpClient udpClient = new UdpClient()){
var gzipMessage = GzipMessage(message);
if (MaxChunkSize < gzipMessage.Length)
{
var chunkCount = gzipMessage.Length / MaxChunkSize + 1;
var messageId = GenerateMessageId(serverHostName);
for (int i = 0; i < chunkCount; i++)
{
var messageChunkPrefix = CreateChunkedMessagePart(messageId, i, chunkCount);
var skip = i * MaxChunkSize;
var messageChunkSuffix = gzipMessage.Skip(skip).Take(MaxChunkSize).ToArray<byte>();
var messageChunkFull = new byte[messageChunkPrefix.Length + messageChunkSuffix.Length];
messageChunkPrefix.CopyTo(messageChunkFull, 0);
messageChunkSuffix.CopyTo(messageChunkFull, messageChunkPrefix.Length);
udpClient.Send(messageChunkFull, messageChunkFull.Length, ipEndPoint);
}
}
else
{
udpClient.Send(gzipMessage, gzipMessage.Length, ipEndPoint);
}
}
}
示例8: listen
private void listen()
{
UdpClient uc = new UdpClient(9527);//udp协议添加端口号
while (true)
{
IPEndPoint ipep = new IPEndPoint(IPAddress.Any,0);//将网络端点转化为ip地址 和端口号
byte[] bmsg = uc.Receive(ref ipep);//返回有远程主机发出的udp数据报
string msg = Encoding.Default.GetString(bmsg);//将字节转化为文本
string[] s = msg.Split('|');//元素分隔
if(s.Length != 4)
{
continue;
}
if(s[0]=="LOGIN")
{
Friend friend=new Friend();
int curIndex = Convert.ToInt32(s[2]);
if (curIndex<0 || curIndex>=this.ilHeadImages.Images.Count)
{
curIndex = 0;
}
friend.HeadImageIndex =curIndex;
friend.NickName = s[1];
friend.Shuoshuo=s[3];
object[] pars=new object[1];
pars[0]=friend;
this.Invoke(new delAddFriend(this.addUcf),pars[0]);
}
}
}
示例9: StopUDPClient
/// <summary>
/// Stops the UDP client.
/// </summary>
/// <param name="udpClient">The UDP client.</param>
public static void StopUDPClient(UdpClient udpClient)
{
if (udpClient != null)
{
udpClient.Close();
}
}
示例10: CreateListener
public static IObservable<UdpReceiveResult> CreateListener(IPAddress remoteAddress, int port)
{
if (remoteAddress == null) throw new ArgumentNullException(nameof(remoteAddress));
if (port < 0 || port > 65535) throw new ArgumentOutOfRangeException(nameof(port), port, null);
IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());
var remoteIPBytes = remoteAddress.GetAddressBytes();
var localAddress =
host.AddressList.FirstOrDefault(ip =>
ip.AddressFamily == remoteAddress.AddressFamily
&& ip.GetAddressBytes().Take(3).SequenceEqual(remoteIPBytes.Take(3)));
if (localAddress == null)
throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Resources.ExceptionMessages.Net_NoInterfaceInSameNetwork, remoteAddress, port));
var localEndPoint = new IPEndPoint(localAddress, port);
var remoteEndPoint = new IPEndPoint(remoteAddress, port);
return Observable.Using(
() =>
{
var client = new UdpClient { ExclusiveAddressUse = false };
client.Client.Bind(localEndPoint);
client.Connect(remoteEndPoint.Address, 0);
return client;
},
client => Observable.While(() => client.Client.Connected, Observable.FromAsync(client.ReceiveAsync)));
}
示例11: Send
public int Send(string sourceIp, string targetIp, int udpPort, TimeSpan delay, TimeSpan duration, List<string> source)
{
var start = DateTime.UtcNow;
var localCounter = 0;
using (var UC = new UdpClient(new IPEndPoint(IPAddress.Parse(sourceIp), 0)))
{
while (DateTime.UtcNow < start.Add(duration))
{
var txtMsg = source[localCounter % source.Count];
var msg = Encoding.ASCII.GetBytes(txtMsg);
var defMatch = SyslogParser.DefaultParser.Match(txtMsg);
var privalMatch = defMatch.Groups["PRIVAL"].Value.Trim();
var prival = int.Parse(privalMatch);
var sent = new SimpleTxSyslog()
{
Sev = (Severity)Enum.ToObject(typeof(Severity), prival & 0x7),
Fac = (Facility)Enum.ToObject(typeof(Facility), prival >> 3),
Message = defMatch.Groups["MESSAGE"].Value.Trim(),
};
this.SentList.Add(sent);
UC.Send(msg, msg.Length, targetIp, udpPort);
localCounter++;
Thread.Sleep(delay);
}
}
return localCounter;
}
示例12: Main
static void Main(string[] args)
{
System.Net.Sockets.UdpClient sock = new System.Net.Sockets.UdpClient();
IPEndPoint iep = new IPEndPoint(IPAddress.Parse("129.241.187.44"), 20004);
Console.WriteLine("Enter message");
string userinput = Console.ReadLine();
byte[] data = Encoding.ASCII.GetBytes(userinput);
sock.Send(data, data.Length, iep);
sock.Close();
Console.WriteLine("Message sent.");
System.Net.Sockets.UdpClient server = new System.Net.Sockets.UdpClient(20004);
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
byte[] recvdata = new byte[1024];
recvdata = server.Receive(ref sender);
server.Close();
string stringData = Encoding.ASCII.GetString(recvdata, 0, recvdata.Length);
Console.WriteLine("Response from " + sender.Address + Environment.NewLine + "Message: " + stringData);
Console.ReadLine();
}
示例13: TestConnectAsync_Success
public void TestConnectAsync_Success()
{
var endPoint = new IPEndPoint( IPAddress.Loopback, 57319 );
var listener = new UdpClient( endPoint );
try
{
using ( var target = new UdpClientTransportManager( new RpcClientConfiguration() ) )
using ( var result = target.ConnectAsync( endPoint ) )
{
Assert.That( result.Wait( TimeSpan.FromSeconds( 1 ) ) );
try
{
var transport = result.Result;
Assert.That( transport.BoundSocket, Is.Not.Null );
Assert.That( ( transport as UdpClientTransport ).RemoteEndPoint, Is.EqualTo( endPoint ) );
}
finally
{
result.Result.Dispose();
}
}
}
finally
{
listener.Close();
}
}
示例14: HardwareReadout
private void HardwareReadout()
{
try
{
//Creates a UdpClient for reading incoming data.
UdpClient receivingUdpClient = new UdpClient(_poort);
//Creates an IPEndPoint to record the IP Address and port number of the sender.
// The IPEndPoint will allow you to read datagrams sent from any source.
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
while (true)
{
byte[] receivedData = receivingUdpClient.Receive(ref RemoteIpEndPoint); // Blocking untill new data
if (NewData != null)
{
// Synchroon
NewData(receivedData);
// Asynchroon
//Task.Factory.StartNew(() => NewData(receivedData));
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Receiver error");
}
}
示例15: Send
public void Send(byte[] datagram, int bytes, IPEndPoint ipEndPoint)
{
using (var udpClient = new UdpClient())
{
udpClient.Send(datagram, bytes, ipEndPoint);
}
}