/// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> /// <remarks> /// Dispose(bool disposing) executes in two distinct scenarios. If disposing equals true, the method has been called directly /// or indirectly by a user's code. Managed and unmanaged resources can be disposed. If disposing equals false, /// the method has been called by the runtime from inside the finalizer and you should not reference other objects. /// Only unmanaged resources can be disposed. /// </remarks> /// <param name="disposing"> /// If disposing equals true, the method has been called directly or indirectly by a user's code. /// </param> protected override void Dispose(bool disposing) { if (this.disposed) { return; } if (disposing) { if (m_Socket != null) { m_Socket.Close(); } } m_Socket = null; // Release unmanaged resources. // Set large fields to null. // Call Dispose on your base class. disposed = true; base.Dispose(true); }
static void Main(string[] args) { int Port = 5150; // Verify arguments if (args.Length < 2 || (args[0] != "IPv4" && args[0] != "IPv6")) { Console.WriteLine("Usage: TCPClient.exe <IPv4 | IPv6> <server name | IPv4 address | IPv6 address> [port]"); return; } if (args.Length >= 3) { Port = System.Convert.ToInt32(args[2].ToString()); } try { Socket MySocket; if (args[0] == "IPv4") { IPHostEntry IPHost = Dns.GetHostByName(args[1].ToString()); Console.Write("Connecting to: "); Console.Write(IPHost.AddressList.GetValue(0).ToString()); Console.WriteLine(":" + Port.ToString()); IPEndPoint ServerEndPoint = new IPEndPoint(IPHost.AddressList[0], Port); MySocket = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP); MySocket.Connect(ServerEndPoint); } else // IPv6 { IPv6Address ServerAddress = IPv6Address.Parse(args[1]); IPv6EndPoint ServerEndPoint = new IPv6EndPoint(ServerAddress, Port); MySocket = new Socket( AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.IP); MySocket.Connect(ServerEndPoint); } String s = "Hello - This is a test"; Byte[] buf = System.Text.Encoding.ASCII.GetBytes(s.ToCharArray()); int BytesSent = MySocket.Send(buf); System.Console.WriteLine("Successfully sent " + BytesSent.ToString() + " byte(s)"); MySocket.Close(); } catch (System.Net.Sockets.SocketException err) { Console.WriteLine("Error: " + err.Message); } }
public void Disconnect() { MySocket.Close(); IsActive = false; }