本文整理汇总了C#中System.Net.Sockets.UdpClient类的典型用法代码示例。如果您正苦于以下问题:C# UdpClient类的具体用法?C# UdpClient怎么用?C# UdpClient使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
UdpClient类属于System.Net.Sockets命名空间,在下文中一共展示了UdpClient类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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;
}
}
}
开发者ID:futjikato,项目名称:ArduinoFanControl,代码行数:30,代码来源:FanUdpServer.cs
示例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();
}
}
开发者ID:IlyichTrue,项目名称:NetSend,代码行数:74,代码来源:NetworkBasic.cs
示例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;
}
开发者ID:janis2013,项目名称:TextVerteilerServerDns,代码行数:25,代码来源:ServerContext.cs
示例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;
}
}
开发者ID:vic-alexiev,项目名称:TrafficDissector,代码行数:30,代码来源:DnsMXForm.cs
示例5: UdpClientAdapter
public UdpClientAdapter(UdpClient udpClient)
{
if (udpClient == null)
throw new ArgumentNullException("udpClient");
_udpClient = udpClient;
}
开发者ID:baminmru,项目名称:vodopad-ip-server,代码行数:7,代码来源:UdpClientAdapter.cs
示例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;
}
开发者ID:Bounz,项目名称:HomeGenie,代码行数:31,代码来源:UdpClient.cs
示例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);
}
}
}
开发者ID:garethky,项目名称:gelf4net,代码行数:31,代码来源:UdpTransport.cs
示例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]);
}
}
}
开发者ID:hytczhoumingxing,项目名称:ct,代码行数:30,代码来源:feigou.cs
示例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();
}
}
开发者ID:andreigec,项目名称:ANDREICSLIB,代码行数:11,代码来源:Networking.cs
示例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)));
}
开发者ID:slorion,项目名称:nlight,代码行数:29,代码来源:UdpConnection.cs
示例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;
}
开发者ID:Reactive-Extensions,项目名称:Tx,代码行数:27,代码来源:SyslogSender.cs
示例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();
}
开发者ID:lepaulse,项目名称:TTK4145-SANNTIDSPROGR-VAAR-2016,代码行数:25,代码来源:Program.cs
示例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();
}
}
开发者ID:Indifer,项目名称:Test,代码行数:28,代码来源:UdpClientTransportManagerTest.cs
示例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");
}
}
开发者ID:jeremysiebers,项目名称:Siebwalde-Source,代码行数:31,代码来源:Receiver.cs
示例15: Send
public void Send(byte[] datagram, int bytes, IPEndPoint ipEndPoint)
{
using (var udpClient = new UdpClient())
{
udpClient.Send(datagram, bytes, ipEndPoint);
}
}
开发者ID:daffers,项目名称:Gelf4NLog,代码行数:7,代码来源:UdpTransportClient.cs
示例16: Listen
public void Listen()
{
using (var udpClient = new UdpClient(_listenPort))
{
_listen = true;
var remoteEp = new IPEndPoint(IPAddress.Any, _listenPort);
while (_listen)
{
var data = udpClient.Receive(ref remoteEp);
if (data.Length <= 0)
{
continue;
}
if (_messageQueue.Count > _messageFloodLimit) //Overflow
{
continue;
}
var rawMessage = new RawMessage()
{
Port = remoteEp.Port,
IpAddress = remoteEp.Address,
Message = System.Text.Encoding.UTF8.GetString(data)
};
_messageQueue.Enqueue(rawMessage);
}
udpClient.Close();
}
}
开发者ID:hammonjj,项目名称:UDPLog,代码行数:32,代码来源:UdpListener.cs
示例17: Connect
private void Connect(IPEndPoint endPoint, int inputDeviceNumber, INetworkChatCodec codec)
{
waveIn = new WaveIn();
waveIn.BufferMilliseconds = 50;
waveIn.DeviceNumber = inputDeviceNumber;
waveIn.WaveFormat = codec.RecordFormat;
waveIn.DataAvailable += waveIn_DataAvailable;
waveIn.StartRecording();
udpSender = new UdpClient();
udpListener = new UdpClient();
// To allow us to talk to ourselves for test purposes:
// http://stackoverflow.com/questions/687868/sending-and-receiving-udp-packets-between-two-programs-on-the-same-computer
udpListener.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
udpListener.Client.Bind(endPoint);
udpSender.Connect(endPoint);
waveOut = new WaveOut();
waveProvider = new BufferedWaveProvider(codec.RecordFormat);
waveOut.Init(waveProvider);
waveOut.Play();
connected = true;
var state = new ListenerThreadState { Codec = codec, EndPoint = endPoint };
ThreadPool.QueueUserWorkItem(ListenerThread, state);
}
开发者ID:LibertyLocked,项目名称:NAudio,代码行数:28,代码来源:NetworkChatPanel.cs
示例18: ServerUDPTunnel
public ServerUDPTunnel(ServerPlayer player)
{
// enstablish an Connection
this.player = player;
udp = new UdpClient(new IPEndPoint(IPAddress.Any, Server.instance.UDPStartPort + (int)player.id));
udp.BeginReceive(onReceive, null);
}
开发者ID:andrefsantos,项目名称:gta-iv-multiplayer,代码行数:7,代码来源:ServerUDPTunnel.cs
示例19: startListen
private bool startListen()
{
try
{
if (tcpListener == null)
tcpListener = new TcpListener(IPAddress.Any, tcpPort);
if (udpClient == null || udpClosed)
{
udpClient = new UdpClient(udpPort);
//udpClient = new UdpClient(udpPort, AddressFamily.InterNetwork);
udpClosed = false;
}
if (udpListenThread == null || !udpListenThread.IsAlive)
{
udpListenThread = new Thread(new ThreadStart(listenForUdpClients));
udpListenThread.IsBackground = true;
udpListenThread.Start();
}
if (tcpListenThread == null || !tcpListenThread.IsAlive)
{
tcpListenThread = new Thread(new ThreadStart(listenForTcpClients));
tcpListenThread.IsBackground = true;
tcpListenThread.Start();
}
Trace.WriteLine("Server started on TCP-Port: " + tcpPort + " and UDP-Port: " + udpPort);
return true;
}
catch
{
Trace.WriteLine("Couldn't start server on Tcp-Port: " + tcpPort + " and Udp-Port: " + udpPort);
return false;
}
}
开发者ID:TeamCDG,项目名称:LocalChat,代码行数:35,代码来源:Peer.cs
示例20: IPhoneSensor
public IPhoneSensor(int port)
{
recievingUdpClient = new UdpClient(port);
RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
calibrateGPS(34.1064,-117.7119);
}
开发者ID:bchasnov,项目名称:Jaguar_Competition,代码行数:7,代码来源:IPhoneSensor.cs
注:本文中的System.Net.Sockets.UdpClient类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论