本文整理汇总了C#中System.Net.Sockets.UdpClient.Close方法的典型用法代码示例。如果您正苦于以下问题:C# UdpClient.Close方法的具体用法?C# UdpClient.Close怎么用?C# UdpClient.Close使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.Sockets.UdpClient
的用法示例。
在下文中一共展示了UdpClient.Close方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: 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();
}
}
示例2: transfer
/*Initiates a TFTP file transfer from the server to the local machine.*/
public bool transfer(IPEndPoint server, String filename, bool error, TransferMode mode)
{
if (DEBUG) { Console.WriteLine("Retrieving file " + filename + " from server at " + server.ToString() + (error ? " with errors " : " without errors ") + "using transfer mode " + (mode == TransferMode.NETASCII ? "netascii." : "octet.")); }
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
byte[] block;
byte[] message = new byte[416];
UInt16 blocknum;
Int32 msgBytes = 0;
Int32 index = 0;
BinaryWriter fileWriter;
UdpClient client = new UdpClient();
fileWriter = new BinaryWriter(File.Create(filename, 512));
requestData(client, server, filename, error, mode);
do
{
block = recieveData(client, ref sender);
if (DEBUG) { Console.WriteLine("Recieved datagram with length " + block.Length + " from " + sender.ToString() + "with op code " + HammingCode.getOpCode(block) + ":\n" + ASCII.GetString(block)); }
if (HammingCode.getOpCode(block) == 3)
{
blocknum = HammingCode.getBlockNum(block);
if (DEBUG) { Console.WriteLine("Recieved data packet with block number: " + blocknum); }
if (HammingCode.getMessage(block, block.Length, ref message, ref msgBytes))
{
fileWriter.Write(message, 0, msgBytes);
index += msgBytes;
acknowledge(client, sender, blocknum);
}
else
{
nacknowledge(client, sender, blocknum);
continue;
}
}
else if (HammingCode.getOpCode(block) == 5) //error
{
Console.WriteLine("Error encountered. Terminating file transfer.");
client.Close();
fileWriter.Close();
File.Delete(filename);
return false;
}
else //wtf?
{
Console.WriteLine("Recieved packet with unexpected op code. Terminating file transfer.");
client.Close();
fileWriter.Close();
File.Delete(filename);
return false;
}
}
while (block.Length > 515);
fileWriter.Close();
return true;
}
示例3: Send
public void Send()
{
var msg = Encoding.ASCII.GetBytes(Message);
try {
var client = new UdpClient();
client.Client.Bind(new IPEndPoint(LocalAddress, 0));
client.BeginSend(msg, msg.Length, EndPoint, result =>
{
try {
client.EndSend(result);
}
catch (Exception ex) {
Debug(ex);
}
finally {
try {
client.Close();
}
catch (Exception) {
}
}
}, null);
}
catch (Exception ex) {
Error(ex);
}
++SendCount;
}
示例4: Discover
public void Discover()
{
m_endpoints = new HashSet<IPEndPoint>();
//m_discover = new UdpClient(new IPEndPoint(IPAddress.Broadcast, RemoteRunner.DiscoverPort));
m_discover = new UdpClient();
m_discover.EnableBroadcast = true;
var endpoint = new IPEndPoint(IPAddress.Broadcast, RemoteRunner.DiscoverPort);
for (int i = 0; i < NumBroadcast; i++)
{
m_discover.Send(RemoteRunner.DiscoverPackage, RemoteRunner.DiscoverPackage.Length, endpoint);
m_discover.BeginReceive(DiscoverCallback, null);
Thread.Sleep(BroadcastDelay);
}
m_discover.Close();
m_clients = new List<TcpClient>();
foreach (var addr in m_endpoints)
{
Console.WriteLine(addr);
var cl = new TcpClient();
cl.BeginConnect(addr.Address, RemoteRunner.ConnectionPort, ConnectCallback, cl);
}
}
示例5: Send
public static void Send(IPAddress source, IPAddress destination, string verb, int fingerprint)
{
using (UdpClient client = new UdpClient(new IPEndPoint(source, 0)))
{
Data.Packet packet = new Data.Packet();
packet.MachineName = Environment.MachineName;
packet.Fingerprint = fingerprint;
packet.Verb = verb;
JavaScriptSerializer serializer = new JavaScriptSerializer();
string jsonData = serializer.Serialize(packet);
byte[] bytes = Encoding.ASCII.GetBytes(jsonData);
IPEndPoint ip = new IPEndPoint(destination, Config.Port);
try
{
client.Send(bytes, bytes.Length, ip);
}
catch (SocketException ex)
{
if (ex.SocketErrorCode == SocketError.HostUnreachable)
//reasoning: we broadcast on all interfaces
//on OS X this may result in No route to host
Console.WriteLine(String.Format("{0}: {1}", source, ex.Message));
else
throw;
}
finally
{
client.Close();
}
}
}
示例6: 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();
}
}
示例7: 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();
}
}
示例8: GetFromTrial
public static int GetFromTrial(string hostname)
{
UdpClient s = new UdpClient();
s.DontFragment = true;
int lo = 1;
int hi = 3000;
// try to find an upper bound
while (trySendUdp(s, hostname, hi))
{
hi <<= 1;
}
// binary search
while (lo != hi)
{
int mid = (lo + hi) >> 1;
if (trySendUdp(s, hostname, mid)) lo = mid + 1;
else hi = mid - 1;
}
// final test
if (!trySendUdp(s, hostname, lo)) lo--;
s.Close();
return lo + 28; // add ip + udp header sizes
}
示例9: HandleBroadcasts
private void HandleBroadcasts()
{
var localIP = new IPEndPoint(IPAddress.Any, 50001);
var udpClient = new UdpClient();
udpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
udpClient.ExclusiveAddressUse = false;
udpClient.Client.Bind(localIP);
var multicastingIP = IPAddress.Parse("228.5.6.7");
udpClient.JoinMulticastGroup(multicastingIP);
running = true;
while (running)
{
var bytes = udpClient.Receive(ref localIP);
var message = Encoding.UTF8.GetString(bytes);
Dispatcher.Invoke(() =>
{
lblResponse.Content = message;
});
}
udpClient.DropMulticastGroup(multicastingIP);
udpClient.Close();
}
示例10: Main
static void Main(string[] args)
{
Console.WriteLine("My First UDP Server ");
string data = "";
UdpClient server = new UdpClient(8008);
IPEndPoint remoteIPEndPoint = new IPEndPoint(IPAddress.Any, 0);
Console.WriteLine(" S E R V E R IS S T A R T E D ");
Console.WriteLine("* Waiting for Client...");
while (data != "q")
{
byte[] receivedBytes = server.Receive(ref remoteIPEndPoint);
data = Encoding.ASCII.GetString(receivedBytes);
Console.WriteLine("Handling client at " + remoteIPEndPoint + " - ");
Console.WriteLine("Message Received " + data.TrimEnd());
server.Send(receivedBytes, receivedBytes.Length, remoteIPEndPoint);
Console.WriteLine("Message Echoed to" + remoteIPEndPoint + data);
}
Console.WriteLine("Press Enter Program Finished");
Console.ReadLine(); //delay end of program
server.Close(); //close the connection
}
示例11: Main
static void Main(string[] args)
{
UdpClient udpClient = new UdpClient(5500);
//udpClient.Connect("raaj.homeip.net", 2005);
udpClient.Connect("192.168.1.8", 2005);
Byte[] sendBytes = Encoding.ASCII.GetBytes("hello?");
udpClient.Send(sendBytes, sendBytes.Length);
//IPEndPoint object will allow us to read datagrams sent from any source.
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
// Blocks until a message returns on this socket from a remote host.
Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint);
string returnData = Encoding.ASCII.GetString(receiveBytes);
// Uses the IPEndPoint object to determine which of these two hosts responded.
Console.WriteLine("This is the message you received " +
returnData.ToString());
Console.WriteLine("This message was sent from " +
RemoteIpEndPoint.Address.ToString() +
" on their port number " +
RemoteIpEndPoint.Port.ToString());
udpClient.Close();
Console.ReadLine();
}
示例12: Worker
protected void Worker()
{
IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName());
try
{
UdpClient udpSocket = new UdpClient(4626);
IPEndPoint ip = new IPEndPoint(IPAddress.Broadcast, 4626);
udpSocket.EnableBroadcast = true;
udpSocket.DontFragment = true;
udpSocket.MulticastLoopback = false;
var add = Dns.GetHostAddresses(Dns.GetHostName()).First(a => a.AddressFamily == AddressFamily.InterNetwork);
var bytes = add.GetAddressBytes();
byte[] port = new byte[2];
port[0] = (byte)(selectedPort & 0x00ff);
port[1] = (byte)((selectedPort >> 8) & 0x00ff);
byte[] buf = bytes.Concat(port).ToArray();
while (_running)
{
udpSocket.Send(buf, buf.Length, ip);
Thread.Sleep(3000);
}
udpSocket.Close();
}
catch (Exception ex)
{
String msg = ex.Message;
}
}
示例13: checkCapacity
public void checkCapacity(String ip,int port,int compacity,int compacityLeft,bool isAlert)
{
try
{
//开始连接
clientSocket = new UdpClient();
IPEndPoint iep = new IPEndPoint(IPAddress.Parse(ip), port);
byte[] sendBytes = this.sendBytes(compacity, compacityLeft, isAlert);
Console.WriteLine(sendBytes[0]+" "+sendBytes[11]);
clientSocket.Send(sendBytes, sendBytes.Length, iep);
byte[] bytes = clientSocket.Receive(ref iep);
string str = Encoding.UTF8.GetString(bytes, 0, bytes.Length);
string message = "来自" + iep.ToString() + "的消息";
Console.WriteLine("message is:"+message);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
finally {
if (clientSocket != null) {
clientSocket.Close();
}
}
}
示例14: Send
public void Send()
{
var msg = Encoding.ASCII.GetBytes(Message);
try {
var client = new UdpClient();
client.Client.Bind(new IPEndPoint(LocalAddress, 0));
client.Ttl = 10;
client.Client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 10);
client.BeginSend(msg, msg.Length, EndPoint, result =>
{
try {
client.EndSend(result);
}
catch (Exception ex) {
_logger.Debug(ex);
}
finally {
try {
client.Close();
}
catch (Exception) {
}
}
}, null);
}
catch (Exception ex) {
_logger.Error(ex);
}
++SendCount;
}
示例15: backgroundWorker1_DoWork
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
IPEndPoint messenger = new IPEndPoint(IPAddress.Any, 0);
bool run = true;
byte[][] whitelist = (byte[][])e.Argument;
UdpClient server = new UdpClient(3444);
serverManager manager = new serverManager(batFilePath, BAT_SERVER_NAME);
while (run)
{
string recievedMessage = Encoding.ASCII.GetString(server.Receive(ref messenger));
byte[] endIPBytes = IPAddress.Parse(messenger.Address.ToString()).GetAddressBytes();
if (checkIP(whitelist, endIPBytes))
{
if (recievedMessage == "quit")
{
run = false;
backgroundWorker1.ReportProgress(1, "Command:" + recievedMessage + ", " + DateTime.Now.ToString() + ", Action: Stopped Listening");
}
else if (recievedMessage == "start")
{
if (manager.isRunning() != true)
{
manager.startServer();
backgroundWorker1.ReportProgress(1, "Command:" + recievedMessage + ", " + DateTime.Now.ToString() + ", Action: started");
}
else
{
backgroundWorker1.ReportProgress(1, "Command:" + recievedMessage + ", " + DateTime.Now.ToString() + ", Action: already started");
}
}
}
}
server.Close();
}