本文整理汇总了C#中System.Net.Sockets.Socket.Dispose方法的典型用法代码示例。如果您正苦于以下问题:C# Socket.Dispose方法的具体用法?C# Socket.Dispose怎么用?C# Socket.Dispose使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.Sockets.Socket
的用法示例。
在下文中一共展示了Socket.Dispose方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: DestorySocket
public static int DestorySocket(Socket socket)
{
int r = -1;
try
{
//if (_socket.Connected)
//{
// _socket.Disconnect(false);
//}
if (socket != null)
{
socket.Shutdown(SocketShutdown.Both);
socket.DisconnectAsync(null);
socket.Close();
socket.Dispose();
socket = null;
}
r = 0;
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
r = -1;
}
return r;
}
示例2: Main
static void Main(string[] args)
{
Console.WriteLine("Witaj w programie wypisujacym informacje o polaczeniu z witryna\n");
Console.WriteLine("Podaj adres witryny: \n");
string adresStrony = Console.ReadLine();
Console.WriteLine("\n");
var adresy = Dns.GetHostAddresses(adresStrony);
var port = 80;
foreach (var adresIp in adresy)
{
var gniazdo = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
gniazdo.Connect(adresIp, port);
Console.WriteLine("Strona: " + adresStrony);
Console.WriteLine("IP serwera: " + ((IPEndPoint)gniazdo.RemoteEndPoint).Address.ToString());
Console.WriteLine("Numer portu zdalnego połączenia: " + ((IPEndPoint)gniazdo.RemoteEndPoint).Port.ToString());
Console.WriteLine("Numer portu lokalnego z którego dokonywane jest połączenie " + ((IPEndPoint)gniazdo.LocalEndPoint).Port.ToString());
}
catch (SocketException)
{
Console.WriteLine("błąd połączenia z portem");
}
finally
{
gniazdo.Dispose();
}
}
Console.ReadKey();
}
示例3: PSTUClient
public PSTUClient()
{
IPAddress ipAddr = IPAddress.Parse(Properties.Settings.Default.IP);
_endPoint = new IPEndPoint(ipAddr, 11000);
_client = new Socket(ipAddr.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
try
{
_client.Connect(_endPoint);
byte[] data = new byte[(1024 * 1024) *5 ];
int length = _client.Receive(data);
if (length > 0)
{
Array.Resize(ref data, length);
var path = "students.xml";
IO.CreateFile(data, path);
Students = File.ReadLines(path).ToArray();
IO.DeleteFile(path);
}
Recieve();
}
catch
{
_client.Dispose();
throw;
}
}
示例4: TrouverPort
//penser gestion erreur
public static int TrouverPort(int nmbreTentatives)
{
int port = -1;
int i =0;
IPAddress ip = GetMyLocalIp();
RandomManager rm = new RandomManager();
while(port==-1 &&i<nmbreTentatives)
{
int t = rm.GetInt(65000);
try
{
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint tempo = new IPEndPoint(ip, t);
s.Bind(tempo);
s.Dispose();
port = t;
}
catch
{
i++;
}
}
return port;
}
示例5: Main
static void Main(string[] args)
{
mServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
IPAddress HostIp = IPAddress.Any;
IPEndPoint iep = new IPEndPoint(HostIp, 2626);
BlinkLog.I("Start Server Socket...");
mServer.Bind(iep);
mServer.Listen(Int32.MaxValue);
mThread = new Thread(Run);
mThread.Start();
}
catch (Exception)
{
BlinkLog.E("Start Server Error.");
}
BlinkLog.I("=========PRESS ANY KEY TO EXIT==========");
Console.ReadKey();
IsExit = true;
if (mThread != null)
{
mThread.Interrupt();
}
mServer.Dispose();
mServer.Close();
}
示例6: Send
public bool Send(byte[] packet, int port)
{
Socket socket = null;
try
{
socket = new Socket(
AddressFamily.InterNetwork,
SocketType.Dgram,
ProtocolType.Udp);
socket.SetSocketOption(
SocketOptionLevel.Socket,
SocketOptionName.ReceiveTimeout,
2000);
var hostEntry = Dns.Resolve(SnmpKeys.RECEIVER_IP);
var endPoint = new IPEndPoint(hostEntry.AddressList[0], port);
socket.SendTo(packet, packet.Length, SocketFlags.None, endPoint);
return true;
}
catch (SocketException)
{
return false;
}
finally
{
if (socket != null)
socket.Dispose();
}
}
示例7: Connect
public async Task Connect(string hostname, int port, Action notifyWhenClosed, int index)
{
_index = index;
var socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
var addresses = Dns.GetHostAddresses(hostname);
var started = false;
foreach (var ipAddress in addresses)
{
if (ipAddress.AddressFamily == AddressFamily.InterNetwork)
{
started = true;
try
{
await socket.ConnectTaskAsync(new IPEndPoint(ipAddress, port));
}
catch (Exception)
{
socket.Dispose();
throw;
}
break;
}
}
if (!started) throw new Exception("Invalid hostname " + hostname); // ipv6 not supported yet
WireStreams(socket, notifyWhenClosed);
}
示例8: Begin
private Socket SOCKET; //receive socket
#endregion Fields
#region Methods
public void Begin()
{
connect:
SOCKET = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
SOCKET.Connect(IPAddress.Parse("127.0.0.1"), 2404);
Console.WriteLine("S104 establish a link successfully, try to receive...");
RCV_THREAD = new System.Threading.Thread(BeginReceive);
RCV_THREAD.Start(SOCKET);
while (true)
{
System.Threading.Thread.Sleep(4000);
this.Send_UFram(Uflag.testfr_active);
if (RCVD_NUM >= 20000)
{
SOCKET.Shutdown(SocketShutdown.Receive);
RCV_THREAD.Abort();
System.Threading.Thread.Sleep(4000);
SOCKET.Shutdown(SocketShutdown.Send);
SOCKET.Dispose();
RCVD_NUM = 0;
goto connect;
}
if (DateTime.Now - lastTime > new TimeSpan(0, 0, 4))
{
this.Send_SFram(RCVD_NUM);
Console.WriteLine("overtime send S fram...");
}
}
}
示例9: Run
static void Run()
{
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress HostIp = IPAddress.Parse("127.0.0.1");
socket.Connect(HostIp, 2626);
BlinkConn conn = Blink.NewConnection(socket, 1024 * 1024, "D:/", Guid.NewGuid().ToString(), 0.001f, null, null);
if (conn != null)
{
Console.WriteLine("Test Send String...");
for (int i = 0; i <= 50; i++)
{
string str = "Test String:" + i;
conn.Send(str);
Console.WriteLine(str);
Thread.Sleep(2);
if (IsExit)
{
conn.Dispose();
socket.Shutdown(SocketShutdown.Both);
socket.Dispose();
socket.Close();
return;
}
}
}
}
示例10: CreateServerAsync
public static Task CreateServerAsync(Func<Socket, Uri, Task> funcAsync, out IPEndPoint localEndPoint, Options options = null)
{
options = options ?? new Options();
try
{
var server = new Socket(options.Address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
server.Bind(new IPEndPoint(options.Address, 0));
server.Listen(options.ListenBacklog);
localEndPoint = (IPEndPoint)server.LocalEndPoint;
string host = options.Address.AddressFamily == AddressFamily.InterNetworkV6 ?
$"[{localEndPoint.Address}]" :
localEndPoint.Address.ToString();
var url = new Uri($"{(options.UseSsl ? "https" : "http")}://{host}:{localEndPoint.Port}/");
return funcAsync(server, url).ContinueWith(t =>
{
server.Dispose();
t.GetAwaiter().GetResult();
}, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default);
}
catch (Exception e)
{
localEndPoint = null;
return Task.FromException(e);
}
}
示例11: CreateConnection
public static async Task<IDisposableConnection<ArraySegment<byte>>> CreateConnection(
EndPoint endpoint,
SocketType socketType = SocketType.Stream,
ProtocolType protocolType = ProtocolType.Tcp)
{
var socket = new Socket(socketType, protocolType);
bool disposeSocket = false;
try
{
using (SocketAwaitableEventArgs args = new SocketAwaitableEventArgs())
{
args.RemoteEndPoint = endpoint;
await socket.ConnectSocketAsync(args);
}
}
catch (Exception)
{
disposeSocket = true;
throw;
}
finally
{
if (disposeSocket)
{
socket.Dispose();
socket = null;
}
}
return socket.ToConnection();
}
示例12: waitForDataToBecomeAvailable
private async Task<bool> waitForDataToBecomeAvailable(int numofmillisecondstowait, Socket youtubeSock)
{
return await Task<bool>.Run(() =>
{
var startTime = DateTime.Now;
var i = 0;
TimeSpan totTime;
while (youtubeSock.Available == 0 && i++ < 150000)
{
//System.Threading.Thread.Sleep(1);
if ((totTime = DateTime.Now.Subtract(startTime)).TotalMilliseconds > numofmillisecondstowait)
{
if (youtubeSock.Connected)
{
youtubeSock.Shutdown(SocketShutdown.Both);
}
youtubeSock.Close();
youtubeSock.Dispose();
LogError("\nwaitForDataToBecomeAvailable() - Dropping http request. Request data took more than 1 sec to send data.\n");
return false;
}
};
return true;
});
}
示例13: CreateUdpMulticastSocket
public IUdpSocket CreateUdpMulticastSocket(string ipAddress, int multicastTimeToLive, int localPort)
{
if (ipAddress == null) throw new ArgumentNullException("ipAddress");
if (ipAddress.Length == 0) throw new ArgumentException("ipAddress cannot be an empty string.", "ipAddress");
if (multicastTimeToLive <= 0) throw new ArgumentException("multicastTimeToLive cannot be zero or less.", "multicastTimeToLive");
if (localPort < 0) throw new ArgumentException("localPort cannot be less than zero.", "localPort");
var retVal = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
try
{
retVal.ExclusiveAddressUse = false;
retVal.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
retVal.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, multicastTimeToLive);
retVal.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Parse(ipAddress), _LocalIP));
retVal.MulticastLoopback = true;
return new UdpSocket(retVal, localPort, _LocalIP.ToString());
}
catch
{
if (retVal != null)
retVal.Dispose();
throw;
}
}
示例14: AbstractSocketChannel
protected AbstractSocketChannel(IChannel parent, Socket socket)
: base(parent)
{
this.Socket = socket;
this.state = StateFlags.Open;
try
{
this.Socket.Blocking = false;
}
catch (SocketException ex)
{
try
{
socket.Dispose();
}
catch (SocketException ex2)
{
if (Logger.WarnEnabled)
{
Logger.Warn("Failed to close a partially initialized socket.", ex2);
}
}
throw new ChannelException("Failed to enter non-blocking mode.", ex);
}
}
示例15: SendingSocketCreator
private Socket SendingSocketCreator(IPEndPoint target)
{
var s = new Socket(target.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
try
{
s.Connect(target);
// Prep the socket so it will reset on close and won't Nagle
s.LingerState = new LingerOption(true, 0);
s.NoDelay = true;
WriteConnectionPreemble(s, Constants.SiloDirectConnectionId); // Identifies this client as a direct silo-to-silo socket
// Start an asynch receive off of the socket to detect closure
var foo = new byte[4];
s.BeginReceive(foo, 0, 1, SocketFlags.None, ReceiveCallback,
new Tuple<Socket, IPEndPoint, SocketManager>(s, target, this));
NetworkingStatisticsGroup.OnOpenedSendingSocket();
}
catch (Exception)
{
try
{
s.Dispose();
}
catch (Exception)
{
// ignore
}
throw;
}
return s;
}