本文整理汇总了C#中System.Net.Sockets.UdpClient.Send方法的典型用法代码示例。如果您正苦于以下问题:C# UdpClient.Send方法的具体用法?C# UdpClient.Send怎么用?C# UdpClient.Send使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.Sockets.UdpClient
的用法示例。
在下文中一共展示了UdpClient.Send方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Main
static void Main(string[] args)
{
Console.WriteLine("Input Desired Port:");
string input = Console.ReadLine();
short port = Int16.Parse(input.Split(' ')[0]);
IPEndPoint cont = null;
IPEndPoint copter = new IPEndPoint(IPAddress.Parse("192.168.1.1"), port);
UdpClient cli = new UdpClient(port);
IPEndPoint remoteHost = null;
while (true)
{
byte[] recieved = cli.Receive(ref remoteHost);
if (remoteHost.Equals(copter))
{
Console.WriteLine("Packet recieved from copter at ({0})", remoteHost);
if (cont != null)
{
Console.WriteLine("Sending to ({0})", cont);
cli.Send(recieved, recieved.Length, cont);
}
}
else
{
cont = remoteHost;
Console.WriteLine("Packet recieved from controller at ({0})", remoteHost);
Console.WriteLine("Sending to ({0})", copter);
cli.Send(recieved, recieved.Length, copter);
}
}
}
示例2: GetServerChallengeSync
public ServerPlayers GetServerChallengeSync(GetServerInfoSettings settings)
{
var localEndpoint = new IPEndPoint(IPAddress.Any, 0);
using (var client = new UdpClient(localEndpoint))
{
client.Client.ReceiveTimeout = settings.ReceiveTimeout;
client.Client.SendTimeout = settings.SendTimeout;
client.Connect(EndPoint);
var requestPacket = new List<byte>();
requestPacket.AddRange(new Byte[] { 0xFF, 0xFF, 0xFF, 0xFF, 0x55 });
requestPacket.AddRange(BitConverter.GetBytes(-1));
client.Send(requestPacket.ToArray(), requestPacket.ToArray().Length);
byte[] responseData = client.Receive(ref localEndpoint);
requestPacket.Clear();
requestPacket.AddRange(new Byte[] { 0xFF, 0xFF, 0xFF, 0xFF, 0x55 });
requestPacket.AddRange(responseData.Skip(5).Take(4));
client.Send(requestPacket.ToArray(), requestPacket.ToArray().Length);
responseData = client.Receive(ref localEndpoint);
return ServerPlayers.Parse(responseData);
}
}
示例3: Loop
protected override void Loop(CancellationToken token)
{
int sequenceNumber = 1;
ConcurrentQueueHelper.Flush(_commandQueue);
using (var udpClient = new UdpClient(CommandPort))
{
udpClient.Connect(_configuration.DroneHostname, CommandPort);
byte[] firstMessage = BitConverter.GetBytes(1);
udpClient.Send(firstMessage, firstMessage.Length);
Stopwatch swKeepAlive = Stopwatch.StartNew();
while (token.IsCancellationRequested == false)
{
ATCommand command;
if (_commandQueue.TryDequeue(out command))
{
byte[] payload = command.CreatePayload(sequenceNumber);
Trace.WriteIf((command is COMWDGCommand) == false, Encoding.ASCII.GetString(payload));
udpClient.Send(payload, payload.Length);
sequenceNumber++;
swKeepAlive.Restart();
}
else if (swKeepAlive.ElapsedMilliseconds > KeepAliveTimeout)
{
_commandQueue.Enqueue(new COMWDGCommand());
}
Thread.Sleep(1);
}
}
}
示例4: Main
static void Main(string[] args)
{
byte[] data = new byte[1024];
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 19511);
UdpClient newsock = new UdpClient(ipep);
Console.WriteLine("Waiting for a client...");
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
data = newsock.Receive(ref sender);
Console.WriteLine("Message received from {0}:", sender.ToString());
Console.WriteLine(Encoding.ASCII.GetString(data, 0, data.Length));
string welcome = "Welcome to my test server";
data = Encoding.ASCII.GetBytes(welcome);
newsock.Send(data, data.Length, sender);
while (true)
{
data = newsock.Receive(ref sender);
Console.WriteLine(Encoding.ASCII.GetString(data, 0, data.Length));
newsock.Send(data, data.Length, sender);
}
}
示例5: 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);
}
}
}
示例6: Indicate
/* sign blink */
static void Indicate(string name, int score)
{
const int LED_COUNT = 126;
UdpClient client = new UdpClient();
/* blue */
byte[] data = new byte[LED_COUNT * 3];
for (int i = 0; i < LED_COUNT; i++)
{
data[i * 3 + 0] = 0x80 + 30;
data[i * 3 + 1] = 0x80;
data[i * 3 + 2] = 0x80;
}
client.Send(data, data.Length, "schild", 10002);
System.Threading.Thread.Sleep(50);
/* blank */
for (int i = 0; i < LED_COUNT; i++)
{
data[i * 3 + 0] = 0x80;
data[i * 3 + 1] = 0x80;
data[i * 3 + 2] = 0x80;
}
client.Send(data, data.Length, "schild", 10002);
}
示例7: DiscoverDevice
public static DiscoveryResult DiscoverDevice(int port) {
IEnumerable<string> ips = getInterfaceAddresses();
var ret = new DiscoveryResult();
_localEndPoint = new IPEndPoint(IPAddress.Any, 0);
_client = new UdpClient(port);
var p = new ISCPPacket("!xECNQSTN");
byte[] sendbuf = p.GetBytes();
foreach (string networkaddress in ips) {
_client.Send(sendbuf, sendbuf.Length, IPAddress.Parse(networkaddress).ToString(), port);
_client.Send(sendbuf, sendbuf.Length, IPAddress.Parse(networkaddress).ToString(), port);
_client.Send(sendbuf, sendbuf.Length, IPAddress.Parse(networkaddress).ToString(), port);
}
while (_client.Available > 0) {
byte[] recv = _client.Receive(ref _localEndPoint);
Thread.Sleep(100);
var sb = new StringBuilder();
foreach (byte t in recv)
sb.Append(char.ConvertFromUtf32(Convert.ToInt32(string.Format("{0:x2}", t), 16)));
string stringData = sb.ToString();
if (stringData.Contains("!1ECN")) {
int idx = stringData.IndexOf("!1ECN") + 5;
string[] parts = stringData.Substring(idx).Split('/');
string mac = parts[3].Substring(0,12);
string ip = ARP.GetIPInfo(mac).IPAddress;
ret.IP = ip;
ret.Port = Convert.ToInt32(parts[1]);
ret.Region = stringData.Substring(idx + 14, 2);
ret.MAC = mac;
ret.Model = stringData.Substring(idx, 7);
}
}
_client.Close();
return ret;
}
示例8: Sender
public Sender(String sprava, String ipString, String portString, String rozlozenieString)
{
int port;
IPAddress ip;
if(IPAddress.TryParse(ipString,out ip) == false)
{
return;
}
if(Int32.TryParse(portString,out port) == false)
{
return;
}
int maxVelkost = Int32.MaxValue;
if (Int32.TryParse(rozlozenieString, out maxVelkost) == false)
{
return;
}
UdpClient client = new UdpClient();
int i = 0;
int pocet = (sprava.Length + maxVelkost -1)/ (maxVelkost) + 1 ;
MessageBox.Show("Počet odoslanych sprav je: " + pocet,"Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
String pocetString = "0000" + pocet.ToString("D4");
try
{
client.Send(Encoding.ASCII.GetBytes(pocetString), pocetString.Length, ip.ToString(), port);
}
catch (Exception ex)
{
Console.WriteLine("chyba: " + ex.Message);
}
for (i = 1; i < pocet; i++)
{
String poradieString = i.ToString("D4");
int koniec = 0;
if (i * maxVelkost > sprava.Length)
{
koniec = sprava.Length - (i-1)*maxVelkost;
}
else
{
koniec = maxVelkost;
}
Byte[] data = Encoding.ASCII.GetBytes(poradieString + sprava.Substring((i-1)*maxVelkost,koniec));
try
{
client.Send(data, data.Length, ip.ToString(), port);
}
catch (Exception ex)
{
Console.WriteLine("chyba: " + ex.Message);
}
}
client.Close();
}
示例9: Search
public void Search()
{
ISearchResponseParser searchResponseParser = new SimpleSearchResponseParser();
var sb = new StringBuilder();
sb.AppendLine("M-SEARCH * HTTP/1.1");
sb.AppendLine("HOST:239.255.255.250:1900");
sb.AppendLine("MAN:\"ssdp:discover\"");
//sb.AppendLine("ST:ssdp:all");
sb.AppendLine("ST: urn:schemas-upnp-org:device:ZonePlayer:1");
sb.AppendLine("MX:3");
sb.AppendLine("");
var searchString = sb.ToString();
var data = Encoding.UTF8.GetBytes(searchString);
udpClient = new UdpClient();
//udpClient.Connect("239.255.255.250", 1900);
udpClient.Send(data, data.Length, "239.255.255.250", 1900);
udpClient.Send(data, data.Length, "255.255.255.255", 1900);
Console.WriteLine("M-Search sent... \r\n");
var timeoutTime = DateTime.UtcNow.Add(searchTimeOut);
searching = true;
while (searching)
{
if (DateTime.UtcNow > timeoutTime)
{
Console.WriteLine("Search Timeout Reached. Starting a new search.");
//udpSocket.Close();
//udpSocket.Dispose();
// Note: this might cause a stack overflow exception because we are recursivley calling this over and over.
// should probably refactor this to use an external timer that starts and stops / disposes.
Search();
}
if (udpClient.Client.Available > 0)
{
var receiveBuffer = new byte[udpClient.Client.Available];
var receivedBytes = udpClient.Client.Receive(receiveBuffer, SocketFlags.None);
if (receivedBytes > 0)
{
var characters = Encoding.UTF8.GetChars(receiveBuffer);
var s = new string(characters);
var serviceDescription = searchResponseParser.Parse(s);
if (ServiceDiscovered != null)
ServiceDiscovered(serviceDescription);
}
}
Thread.Sleep(100);
//UdpSocket.SendTo(Encoding.UTF8.GetBytes(searchString), SocketFlags.None, MulticastEndPoint);
}
}
示例10: frmMain_FormClosed
private void frmMain_FormClosed(object sender, FormClosedEventArgs e)
{
UdpClient uc = new UdpClient();
string msg = "LOGOUT";
byte[] bmsg = Encoding.Default.GetBytes(msg);
uc.Send(bmsg, bmsg.Length, new IPEndPoint(IPAddress.Parse("255.255.255.255"), 9527));
}
示例11: doThread
/// <summary>
/// Функция-обработчик потока
/// </summary>
protected void doThread()
{
UdpClient udpClient = new UdpClient();
try
{
IsWorking = true;
byte[] bytes = Encoding.UTF8.GetBytes("<server-request>");
List<IPAddress> broadcastIp = AddressProvider.GetBroadcastIp();
while (mustWork)
{
foreach (IPAddress ip in broadcastIp)
{
IPEndPoint endPoint = new IPEndPoint(ip, 11000);
udpClient.Send(bytes, bytes.Length, endPoint);
}
Thread.Sleep(1000);
}
}
catch (ExceptionServer e)
{
}
finally
{
IsWorking = false;
}
}
示例12: SendData
public static void SendData(Program ProgramCur,Patient pat) {
if(pat==null) {
MsgBox.Show("EvaSoft","You must select a patient first.");
return;
}
Process[] evaSoftInstances=Process.GetProcessesByName("EvaSoft");
if(evaSoftInstances.Length==0) {
MsgBox.Show("EvaSoft","EvaSoft is not running. EvaSoft must be running before the bridge will work.");
return;
}
ArrayList ForProgram=ProgramProperties.GetForProgram(ProgramCur.ProgramNum);
UdpClient udpClient=new UdpClient();
string udpMessage="REQUEST01123581321~~~0.1b~~~pmaddpatient~~~";
//Patient id can be any string format
ProgramProperty PPCur=ProgramProperties.GetCur(ForProgram,"Enter 0 to use PatientNum, or 1 to use ChartNum");
if(PPCur.PropertyValue=="0") {
udpMessage+=pat.PatNum.ToString();
}
else {
udpMessage+=pat.ChartNumber.Replace(",","").Trim();//Remove any commas. Not likely to exist, but just to be safe.
}
udpMessage+=","+pat.FName.Replace(",","").Trim();//Remove commas from data, because they are the separator.
udpMessage+=","+pat.LName.Replace(",","").Trim();//Remove commas from data, because they are the separator.
udpMessage+=","+pat.Birthdate.ToString("MM/dd/yyyy");
udpMessage+=","+((pat.Gender==PatientGender.Female)?"female":"male");
udpMessage+=","+(pat.Address+" "+pat.Address2).Replace(",","").Trim();//Remove commas from data, because they are the separator.
udpMessage+=","+pat.City.Replace(",","").Trim();//Remove commas from data, because they are the separator.
udpMessage+=","+pat.State.Replace(",","").Trim();//Remove commas from data, because they are the separator.
udpMessage+=","+pat.Zip.Replace(",","").Trim();//Remove commas from data, because they are the separator.
byte[] udpMessageBytes=Encoding.ASCII.GetBytes(udpMessage);
udpClient.Send(udpMessageBytes,udpMessageBytes.Length,"localhost",35678);
}
示例13: connect
//metoda koja šalje poruku čvoru koji sadrži traženu datoteku
public void connect(string destination, string fileName, string udpPort)
{
ip = destination;
this.fileToDownload = fileName;
//kreiranje polja bajtova u koje se spremaju podaci koji se šalju korisniku
//(ime datoteke, veličina datoteke i veličina imena)
byte[] data = new byte[4096];
try
{
//dohvaćanje porta na koji se šalju podaci
int portNumber = Convert.ToInt32(udpPort);
//parsiranje IP adrese iz stringa
ip = ip.Replace(" ", string.Empty);
IPAddress ipaddr = IPAddress.Parse(this.ip);
//kreiranje UDP klijenta i IPEndPointa koji šalju podatke
UdpClient server = new UdpClient();
IPEndPoint sender = new IPEndPoint(ipaddr, portNumber);
//kreiranje poruke koja se šalje i njeno kodiranje u bajtove
string welcome = "D" + helper.portTCP + ":" + this.fileToDownload;
data = Encoding.ASCII.GetBytes(welcome);
//slanje poruke (podaci, veličina podataka, podaci o računalu)
server.Send(data, data.Length, sender);
}
//hvatanje izinmke
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.ToString());
}
}
示例14: StartPerfmonCollectionLoop
private static void StartPerfmonCollectionLoop()
{
var counters = new PerformanceCounters("");
var syslogForwarder = new UdpClient();
syslogForwarder.Connect(ConfigurationManager.AppSettings["forward_host"], int.Parse(ConfigurationManager.AppSettings["forward_port"]));
var sw = Stopwatch.StartNew();
while (true)
{
sw.Restart();
foreach (var counter in counters)
{
var nextValue = counter.NextValue();
var timestamp = DateTime.Now;
var datagram = GetSyslogDatagram(counter, nextValue, timestamp);
var bytesSend = syslogForwarder.Send(datagram, datagram.Length);
log.Debug("Sending " + datagram.Length + " bytes");
if (bytesSend != datagram.Length)
{
log.ErrorFormat("bytes sent " + bytesSend + " does not equal datagram length " + datagram.Length);
}
}
sw.Stop();
log.Info(string.Format("Queried {0} counters in {1} ms", counters.Count, sw.Elapsed.TotalMilliseconds));
Thread.Sleep(10 * 1000);
}
}
示例15: UdpEchoClientMethod
void UdpEchoClientMethod(string[] args)
{
//Check for correct amount of arguments.
if ((args.Length < 2) || (args.Length > 3))
throw new ArgumentException("Parameters: <Server> <Word> [<Port>]");
//Name/IPAddress
string server = args[0];
//Use port argument if supplied, otherwise default to 7
int servPort = (args.Length == 3) ? Int32.Parse(args[2]) : 7;
//Convert input string to an array of bytes.
byte[] sendPacket = Encoding.ASCII.GetBytes(args[1]);
//Create a UdpClient instance
UdpClient client = new UdpClient();
try
{
//Send the echo string(packet) to the specified host and port
client.Send(sendPacket, sendPacket.Length, server, servPort);
Console.WriteLine("Sent {0} bytes to the server...", sendPacket.Length);
//This IPEndPoint instance will be populated with the remote sender's endpoint information after the Receive() call
IPEndPoint remoteIPEndPoint = new IPEndPoint(IPAddress.Any, 0);
//Attempt echo reply receive
byte[] rcvPacket = client.Receive(ref remoteIPEndPoint);
Console.WriteLine("Received {0} bytes from {1}: {2}", rcvPacket.Length, remoteIPEndPoint, Encoding.ASCII.GetString(rcvPacket, 0, rcvPacket.Length));
}
catch (SocketException se)
{
Console.WriteLine(se.ErrorCode + ": " + se.Message);
}
client.Close();
}