本文整理汇总了C#中System.Net.Sockets.Socket.Close方法的典型用法代码示例。如果您正苦于以下问题:C# Socket.Close方法的具体用法?C# Socket.Close怎么用?C# Socket.Close使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.Sockets.Socket
的用法示例。
在下文中一共展示了Socket.Close方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Main
static void Main(string[] args)
{
byte[] receiveBytes = new byte[1024];
int port =8080;//服务器端口
string host = "10.3.0.1"; //服务器ip
IPAddress ip = IPAddress.Parse(host);
IPEndPoint ipe = new IPEndPoint(ip, port);//把ip和端口转化为IPEndPoint实例
Console.WriteLine("Starting Creating Socket Object");
Socket sender = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);//创建一个Socket
sender.Connect(ipe);//连接到服务器
string sendingMessage = "Hello World!";
byte[] forwardingMessage = Encoding.ASCII.GetBytes(sendingMessage + "[FINAL]");
sender.Send(forwardingMessage);
int totalBytesReceived = sender.Receive(receiveBytes);
Console.WriteLine("Message provided from server: {0}",
Encoding.ASCII.GetString(receiveBytes,0,totalBytesReceived));
//byte[] bs = Encoding.ASCII.GetBytes(sendStr);
sender.Shutdown(SocketShutdown.Both);
sender.Close();
Console.ReadLine();
}
示例2: ConnectIPAddressAny
public void ConnectIPAddressAny ()
{
IPEndPoint ep = new IPEndPoint (IPAddress.Any, 0);
/* UDP sockets use Any to disconnect
try {
using (Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) {
s.Connect (ep);
s.Close ();
}
Assert.Fail ("#1");
} catch (SocketException ex) {
Assert.AreEqual (10049, ex.ErrorCode, "#2");
}
*/
try {
using (Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) {
s.Connect (ep);
s.Close ();
}
Assert.Fail ("#3");
} catch (SocketException ex) {
Assert.AreEqual (10049, ex.ErrorCode, "#4");
}
}
示例3: Main
static void Main(string[] args)
{
IPAddress[] addresses = Dns.GetHostAddresses("38.98.173.2");
//IPAddress[] addresses = Dns.GetHostAddresses("127.0.0.1");
IPEndPoint _ipEndpoint = new IPEndPoint(addresses[0], 58642);
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("38.98.173.2"), 58642);
Socket _socket = new Socket(_ipEndpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
IAsyncResult result = _socket.BeginConnect(_ipEndpoint, null, null);
bool success = result.AsyncWaitHandle.WaitOne(2000, true);
if (!success)
{
_socket.Close();
Console.WriteLine("failed to connect");
//throw new ApplicationException("Timeout trying to connect to server!");
}
if (_socket.Connected)
{
Console.WriteLine("connected!");
//send a byte to let the server know that this is the data loader program communicating with it
byte[] clientTypeByte = new byte[1024];
for(int i=0;i<1024;i++)
clientTypeByte[i] = (byte)(i%256);
_socket.Send(clientTypeByte);
byte[] dataFromServer = new byte[1024];
int bytesReceived = _socket.Receive(dataFromServer);
_socket.Close();
}
Console.ReadLine();
}
示例4: RefreshTorIdentity
public void RefreshTorIdentity()
{
Socket server = null;
try
{
IPEndPoint ip = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9151);
server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
server.Connect(ip);
// Please be sure that you have executed the part with the creation of an authentication hash, described in my article!
server.Send(Encoding.ASCII.GetBytes("AUTHENTICATE \"johnsmith\"" + Environment.NewLine));
byte[] data = new byte[1024];
int receivedDataLength = server.Receive(data);
string stringData = Encoding.ASCII.GetString(data, 0, receivedDataLength);
server.Send(Encoding.ASCII.GetBytes("SIGNAL NEWNYM" + Environment.NewLine));
data = new byte[1024];
receivedDataLength = server.Receive(data);
stringData = Encoding.ASCII.GetString(data, 0, receivedDataLength);
if (!stringData.Contains("250"))
{
Console.WriteLine("Unable to signal new user to server.");
server.Shutdown(SocketShutdown.Both);
server.Close();
}
}
finally
{
server.Close();
}
}
示例5: ConnectToServerWithTimeout
/// <summary>
/// This code is used to connect to a TCP socket with timeout option.
/// </summary>
/// <param name="endPoint">IP endpoint of remote server</param>
/// <param name="timeoutMs">Timeout to wait until connect</param>
/// <returns>Socket object connected to server</returns>
public static Socket ConnectToServerWithTimeout(EndPoint endPoint, int timeoutMs)
{
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
socket.Blocking = false;
socket.Connect(endPoint);
socket.Blocking = true;
return socket;
}
catch (SocketException socketException)
{
if (socketException.ErrorCode != 10035)
{
socket.Close();
throw;
}
if (!socket.Poll(timeoutMs * 1000, SelectMode.SelectWrite))
{
socket.Close();
throw new NGRIDException("The host failed to connect. Timeout occured.");
}
socket.Blocking = true;
return socket;
}
}
示例6: ProcessConnection
private void ProcessConnection(Socket socket)
{
const int minCharsCount = 3;
const int charsToProcess = 64;
const int bufSize = 1024;
try {
if (!socket.Connected) return;
var data = "";
while (true) {
var bytes = new byte[bufSize];
var recData = socket.Receive(bytes);
data += Encoding.ASCII.GetString(bytes, 0, recData);
if (data.Length >= charsToProcess) {
var str = data.Take(charsToProcess);
var charsTable = str.Distinct()
.ToDictionary(c => c, c => str.Count(x => x == c));
if (charsTable.Count < minCharsCount) {
var message = $"Server got only {charsTable.Count} chars, closing connection.<EOF>";
socket.Send(Encoding.ASCII.GetBytes(message));
socket.Close();
break;
}
var result = String.Join(", ",
charsTable.Select(c => $"{c.Key}: {c.Value}"));
Console.WriteLine($"Sending {result}\n");
socket.Send(Encoding.ASCII.GetBytes(result + "<EOF>"));
data = String.Join("", data.Skip(charsToProcess));
}
}
} finally {
socket.Close();
}
}
示例7: JTAGSerialStream2
public JTAGSerialStream2(string Cable, int Device, int Instance)
{
try
{
Socket SerialListenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint SerialEP = new IPEndPoint(IPAddress.Any, 0);
SerialListenSocket.Bind(SerialEP);
SerialListenSocket.Listen(1);
SerialEP = (IPEndPoint)SerialListenSocket.LocalEndPoint;
SerialProcess = new Process();
SerialProcess.StartInfo.FileName = "quartus_stp";
SerialProcess.StartInfo.Arguments = String.Format("-t serial.tcl \"{0}\" {1} {2} {3}", Cable, Device, Instance, SerialEP.Port);
SerialProcess.EnableRaisingEvents = true;
SerialProcess.Exited +=
delegate(object Sender, EventArgs e)
{
if (SerialListenSocket != null)
SerialListenSocket.Close();
};
SerialProcess.Start();
SerialSocket = SerialListenSocket.Accept();
SerialListenSocket.Close();
SerialListenSocket = null;
}
catch (System.ComponentModel.Win32Exception e)
{
throw new JTAGException(String.Format("Error starting JTAG serial process: {0}", e.Message));
}
}
示例8: addClass
public bool addClass(string hostName, int hostPort, string appName, string className, string classTitle)
{
IPAddress host = IPAddress.Parse(hostName);
IPEndPoint hostep = new IPEndPoint(host, hostPort);
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
sock.Connect(hostep);
}
catch (SocketException e)
{
Console.WriteLine("Problem connecting to host");
Console.WriteLine(e.ToString());
if (sock.Connected)
{
sock.Close();
}
}
try {
response = sock.Send(Encoding.ASCII.GetBytes("type=SNP#?version=1.0#?action=add_class#?app=" + appName + "#?class=" + className + "#?title=" + classTitle));
response = sock.Send(Encoding.ASCII.GetBytes("\r\n"));
}
catch (SocketException e)
{
Console.WriteLine(e.ToString());
}
sock.Close();
return true;
}
示例9: NTPTime
/// <summary>
/// Try to update both system and RTC time using the NTP protocol
/// </summary>
/// <param name="TimeServer">Time server to use, ex: pool.ntp.org</param>
/// <param name="GmtOffset">GMT offset in minutes, ex: -240</param>
/// <returns>Returns true if successful</returns>
public DateTime NTPTime(string TimeServer, int GmtOffset = 0)
{
Socket s = null;
DateTime resultTime = DateTime.Now;
try
{
EndPoint rep = new IPEndPoint(Dns.GetHostEntry(TimeServer).AddressList[0], 123);
s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
byte[] ntpData = new byte[48];
Array.Clear(ntpData, 0, 48);
ntpData[0] = 0x1B; // Set protocol version
s.SendTo(ntpData, rep); // Send Request
if (s.Poll(30 * 1000 * 1000, SelectMode.SelectRead)) // Waiting an answer for 30s, if nothing: timeout
{
s.ReceiveFrom(ntpData, ref rep); // Receive Time
byte offsetTransmitTime = 40;
ulong intpart = 0;
ulong fractpart = 0;
for (int i = 0; i <= 3; i++) intpart = (intpart << 8) | ntpData[offsetTransmitTime + i];
for (int i = 4; i <= 7; i++) fractpart = (fractpart << 8) | ntpData[offsetTransmitTime + i];
ulong milliseconds = (intpart * 1000 + (fractpart * 1000) / 0x100000000L);
s.Close();
resultTime = new DateTime(1900, 1, 1) + TimeSpan.FromTicks((long)milliseconds * TimeSpan.TicksPerMillisecond);
Utility.SetLocalTime(resultTime.AddMinutes(GmtOffset));
}
s.Close();
}
catch
{
try { s.Close(); }
catch { }
}
return resultTime;
}
示例10: Connect
private void Connect()
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
{
SendTimeout = SendTimeout,
ReceiveTimeout = ReceiveTimeout
};
try
{
if (ConnectTimeout == 0)
{
socket.Connect(Host, Port);
}
else
{
var connectResult = socket.BeginConnect(Host, Port, null, null);
connectResult.AsyncWaitHandle.WaitOne(ConnectTimeout, true);
}
if (!socket.Connected)
{
socket.Close();
socket = null;
return;
}
Bstream = new BufferedStream(new NetworkStream(socket), 16 * 1024);
if (Password != null)
SendExpectSuccess(Commands.Auth, Password.ToUtf8Bytes());
db = 0;
var ipEndpoint = socket.LocalEndPoint as IPEndPoint;
clientPort = ipEndpoint != null ? ipEndpoint.Port : -1;
lastCommand = null;
lastSocketException = null;
LastConnectedAtTimestamp = Stopwatch.GetTimestamp();
if (isPreVersion1_26 == null)
{
isPreVersion1_26 = this.ServerVersion.CompareTo("1.2.6") <= 0;
}
if (ConnectionFilter != null)
{
ConnectionFilter(this);
}
}
catch (SocketException ex)
{
if (socket != null)
socket.Close();
socket = null;
HadExceptions = true;
var throwEx = new RedisException("could not connect to redis Instance at " + Host + ":" + Port, ex);
log.Error(throwEx.Message, ex);
throw throwEx;
}
}
示例11: ScanAsync
public async Task<IEnumerable<string>> ScanAsync() {
var result = new List<string>();
var vcmd = "host:version";
var okay = "OKAY0004001d";
foreach(var item in NetworkInterface.GetAllNetworkInterfaces()) {
if(item.NetworkInterfaceType == NetworkInterfaceType.Loopback || item.OperationalStatus != OperationalStatus.Up) continue;
this.LogDebug("Scanning network interface: {0}", item.Description);
UnicastIPAddressInformationCollection UnicastIPInfoCol = item.GetIPProperties().UnicastAddresses;
foreach(UnicastIPAddressInformation UnicatIPInfo in UnicastIPInfoCol) {
try {
var gateway = item.GetIPProperties().GatewayAddresses.First().Address;
var range = new IPAddressRange("{0}/{1}".With(gateway, UnicatIPInfo.IPv4Mask));
foreach(var ip in range.Addresses.Skip(110)) {
for(var port = 5550; port < 5560; port++) {
this.LogDebug("Connecting to {0}:{1}", ip, port);
using(var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) {
try {
socket.Blocking = true;
var aresult = socket.BeginConnect(ip, port, null, null);
bool success = aresult.AsyncWaitHandle.WaitOne(200, true);
if(!success) {
this.LogWarn("Connection Timeout");
socket.Close();
continue;
}
this.LogDebug("Connection successful: {0}:{1}", ip, port);
var b = new byte[12];
var data = "{0}{1}\n".With(vcmd.Length.ToString("X4"), vcmd).GetBytes();
var count = socket.Send(data, 0, data.Length, SocketFlags.None);
if(count == 0) {
throw new InvalidOperationException("Unable to send version command to adb");
}
socket.ReceiveBufferSize = 4;
count = socket.Receive(b,0,4, SocketFlags.None);
var msg = b.GetString();
if(string.Compare(msg, okay, false) == 0) {
result.Add("{0}:{1}".With(ip.ToString(), port));
break;
}
socket.Close();
} catch(InvalidOperationException ioe) {
this.LogError(ioe.Message, ioe);
}
}
}
}
} catch(Exception ex) {
this.LogError(ex.Message, ex);
}
}
}
return result;
}
示例12: LinkEQP
private string gsProgrammerMail = ConfigurationManager.AppSettings.Get("ProgrammerMail"); //從AppConfig讀取「ProgrammerMail」參數
#endregion Fields
#region Methods
/// <summary>
/// 連線或斷線至ModBusToEthernet設備
/// iStatus = 0,則連線
/// iStatus = 1,則斷線
/// </summary>
/// <param name="iStatus">0為連線、1為斷線</param>
/// <param name="sIP">設備的IP位址</param>
/// <param name="sIPPort">設備的IP_Port</param>
public bool LinkEQP(int iStatus, string sIP, string sIPPort, Socket gWorkSocket)
{
bool blFlag = false;
try
{
switch (iStatus)
{
case 0:
// Set the timeout for synchronous receive methods to
// 1 second (1000 milliseconds.)
gWorkSocket.ReceiveTimeout = giReceiveTimeout * 1000;
// Set the timeout for synchronous send methods
// to 1 second (1000 milliseconds.)
gWorkSocket.SendTimeout = giSendTimeout * 1000;
if (gWorkSocket.Connected == true)
{
gWorkSocket.Shutdown(SocketShutdown.Both);
gWorkSocket.Close();
}
else if (gWorkSocket.Connected == false)
{
gWorkSocket.Connect(sIP, Convert.ToInt32(sIPPort));
if ((gWorkSocket.Connected == true))
{
//System.Threading.Thread.Sleep(150);
gLogger.Trace("ModbusRTU--成功連結 to:" + sIP);
}
}
blFlag = true;
break;
case 1:
if ((gWorkSocket.Connected == true))
{
gWorkSocket.Shutdown(SocketShutdown.Both);
gWorkSocket.Close();
//System.Threading.Thread.Sleep(150);
gLogger.Trace("ModbusRTU--取消連線 to:" + sIP);
}
blFlag = false;
break;
}
}
catch (Exception ex)
{
gLogger.ErrorException("ModbusTCP.LinkEQP:", ex);
if (gWorkSocket.Connected)
{
gWorkSocket.Shutdown(SocketShutdown.Both);
gWorkSocket.Close();
}
throw ex;
}
return blFlag;
}
示例13: StartClient
public static void StartClient(string ip, string data)
{
// Data buffer for incoming data.
byte[] bytes = new byte[1024];
// Connect to a remote device.
try
{
// Establish the remote endpoint for the socket.
// This example uses port 11000 on the local computer.
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = IPAddress.Parse(ip);
IPEndPoint remoteEP = new IPEndPoint(ipAddress, 15001);
// Create a TCP/IP socket.
Socket sender = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// Connect the socket to the remote endpoint. Catch any errors.
try
{
sender.Connect(remoteEP);
Console.WriteLine("Socket connected to {0}",
sender.RemoteEndPoint.ToString());
// Encode the data string into a byte array.
byte[] msg = Encoding.ASCII.GetBytes(data + "<EOF>");
// Send the data through the socket.
int bytesSent = sender.Send(msg);
// Receive the response from the remote device.
int bytesRec = sender.Receive(bytes);
Console.WriteLine("Echoed test = {0}",
Encoding.ASCII.GetString(bytes, 0, bytesRec));
// Release the socket.
sender.Shutdown(SocketShutdown.Both);
sender.Close();
Console.WriteLine("finish " + DateTime.Now);
}
catch (Exception e)
{
sender.Shutdown(SocketShutdown.Both);
sender.Close();
Console.WriteLine("Unexpected exception : {0}", e.ToString());
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
示例14: btnEnter_Click
private void btnEnter_Click(object sender, EventArgs e)
{
clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 6666);
clientSocket.SendBufferSize = 1024;
clientSocket.ReceiveBufferSize = 1024;
try
{
clientSocket.Connect(ipep);
Regex reg = new Regex(@"^[a-zA-Z0-9_]+$");
userName = textName.Text;
//Check whether the name only consisits of letters,numbers,underlines
if (reg.IsMatch(userName))
{
byte[] nameByte = new byte[1024];
Encoding.UTF8.GetBytes(userName,0,userName.Length,nameByte,0);
clientSocket.Send(nameByte);
byte[] answerByte = new byte[1024];
clientSocket.Receive(answerByte);
string answer = Encoding.UTF8.GetString(answerByte).Trim(new char[] { '\0' });
if (answer == "NameErr")
{
//fail to log in
MessageBox.Show(userName + "has been used.\r\nPlease try another one.");
textName.Clear();
clientSocket.Close();
}
else if (answer == "NameSuc")
{
//log in successfully
this.DialogResult = DialogResult.OK;
}
}
else
{
MessageBox.Show("Only letters,numbers,underlines are allowed");
textName.Clear();
clientSocket.Close();
}
}
catch (SocketException)
{
//When the server isn't started
MessageBox.Show("Disconnected to the server");
this.Close();
Application.Exit();
}
}
示例15: verify
public static bool verify(string address)
{
string[] host = (address.Split('@'));
string hostname = host[1];
//string hostStr = "smtp.net4india.com";
IPHostEntry IPhst = Dns.GetHostEntry(hostname);
//Dns.GetHostByName
IPEndPoint endPt = new IPEndPoint(IPhst.AddressList[0],25);
Socket s = new Socket(endPt.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
s.Connect(endPt);
//Attempting to connect
if (!Check_Response(s, SMTPResponse.CONNECT_SUCCESS))
{
s.Close();
return false;
}
//HELO server
Senddata(s, string.Format("HELO {0}\r\n", Dns.GetHostName()));
if (!Check_Response(s, SMTPResponse.GENERIC_SUCCESS))
{
s.Close();
return false;
}
//Identify yourself
//Servers may resolve your domain and check whether
//you are listed in BlackLists etc.
Senddata(s, string.Format("MAIL From: {0}\r\n",
"[email protected]"));
if (!Check_Response(s, SMTPResponse.GENERIC_SUCCESS))
{
s.Close();
return false;
}
//Attempt Delivery (I can use VRFY, but most
//SMTP servers only disable it for security reasons)
Senddata(s, address);
if (!Check_Response(s, SMTPResponse.GENERIC_SUCCESS))
{
s.Close();
return false;
}
return (true);
}