public void TryPrint(string zplCommands) { try { // Open connection System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient(); client.Connect(this.m_IPAddress, this.m_Port); // Write ZPL String to connection System.IO.StreamWriter writer = new System.IO.StreamWriter(client.GetStream()); writer.Write(zplCommands); writer.Flush(); // Close Connection writer.Close(); client.Close(); } catch (Exception ex) { this.m_ErrorCount += 1; if(this.m_ErrorCount < 10) { System.Threading.Thread.Sleep(5000); this.TryPrint(zplCommands); } else { throw ex; } } }
bool TryConnect(string hostname, System.Net.IPAddress ip, int port, int connectTimeout) { //EB.Debug.Log("Try connect {0}:{1}", ip, port); if (_client.Client.AddressFamily != ip.AddressFamily) { _client.Close(); _client = new System.Net.Sockets.TcpClient(ip.AddressFamily); _client.NoDelay = true; } var async = _client.BeginConnect(ip, port, null, null); if (!async.AsyncWaitHandle.WaitOne(System.TimeSpan.FromMilliseconds(connectTimeout))) { _error = NetworkFailure.TimedOut; return(false); } if (!async.IsCompleted) { _error = NetworkFailure.TimedOut; return(false); } _client.EndConnect(async); if (_client.Connected == false) { EB.Debug.LogError("Failed to connect to {0}:{1}", ip, port); _error = NetworkFailure.CannotConnectToHost; return(false); } OnConnected(); _net = _client.GetStream(); _stream = _net; if (_secure) { //EB.Debug.Log("Doing ssl connect {0}:{1}", ip, port); _ssl = new System.Net.Security.SslStream(_stream, true, RemoteCertificateValidationCallback, null); try { _ssl.AuthenticateAsClient(hostname); } catch (System.Exception e) { EB.Debug.LogError("Failed to authenticate: " + e); return(false); } _stream = _ssl; } //EB.Debug.Log("Connected to {0}:{1}", ip, port); LastTime = System.DateTime.Now; return(true); }
/// <include file='InterfaceDocumentationComments.xml' path='doc/members/member[@name="M:FrameworkAbstraction.ITcpClient.Close"]/*'/> public void Close() { if (tcpClient.Connected == true) { tcpClient.Client.Shutdown(System.Net.Sockets.SocketShutdown.Send); tcpClient.Client.Disconnect(false); } tcpClient.Close(); tcpClient = null; }
private void button1_Click(object sender, RoutedEventArgs e) { System.Text.Encoding enc = System.Text.Encoding.UTF8; string host = textBox2.Text.Trim(); int port = int.Parse(textBox3.Text); try { System.Net.Sockets.TcpClient tcp = new System.Net.Sockets.TcpClient(host, port); System.Net.Sockets.NetworkStream ns = tcp.GetStream(); string sendMsg = textBox1.Text; if (sendMsg == "" || textBox1.Text.Length > 140) { textBlock1.Text = "ツイートできる条件を満たしてません!!"; tcp.Close(); return; } byte[] sendBytes = enc.GetBytes(sendMsg + '\n'); ns.Write(sendBytes, 0, sendBytes.Length); //TCPソケットサーバーからストリームが送られてくる場合に受け取れるように if (checkBox1.IsChecked == true) { System.IO.MemoryStream ms = new System.IO.MemoryStream(); byte[] resBytes = new byte[256]; int resSize; do { resSize = ns.Read(resBytes, 0, resBytes.Length); if (resSize == 0) { textBlock1.Text = "サーバーが切断しました。"; return; } ms.Write(resBytes, 0, resSize); } while (ns.DataAvailable);//TODO:RubyのTCPSocketのputsメソッドに対応していない string resMsg = enc.GetString(ms.ToArray()); textBlock1.Text = resMsg; ms.Close(); } ns.Close(); tcp.Close(); textBlock1.Text = host + "のmikutterでつぶやきました。"; textBox1.Text = ""; } catch (Exception ex) { MessageBox.Show(ex.ToString(),"Error"); Environment.Exit(1); } }
private void bt_delete_SM_Click(object sender, EventArgs e) { Variable.Tab_sec = Variable.Tab_default; //int sm_id=0; //sm_id = int.Parse(cb_sm_list.SelectedValue.ToString()); // MessageBox.Show("inside delete"); if (Variable.sm_id == "0") { MessageBox.Show("Need to select Security Manager Before Delete Operation"); } else { Data_send = "Admin_Delete_SM|" + Variable.gusername + "|" + Variable.sm_id; // MessageBox.Show(Data_send); try { clientSocket2.Connect(Variable.ipaddress, Variable.port); STR_W = new StreamWriter(clientSocket2.GetStream()); STR_R = new StreamReader(clientSocket2.GetStream()); STR_W.AutoFlush = true; if (clientSocket2.Connected) { STR_W.WriteLine(Data_send); string returndata; returndata = STR_R.ReadLine(); if (returndata == "Success") { MessageBox.Show("Selected Security manager has been deleted"); this.Hide(); //MessageBox.Show("User has been successfully Logout"); AdminHome form2 = new AdminHome(); form2.Closed += (s, args) => this.Close(); form2.Show(); } else { MessageBox.Show("Error in Operations"); } clientSocket2.Close(); } } catch (Exception e1) { MessageBox.Show(e1.ToString()); clientSocket2.Close(); } } }
private void TryClose() { if (!longConnection) { if (client.Client != null) { client.Client.Close(); } if (client != null) { client.Close(); } client = null; } }
/// <summary> /// 在web访问到来时取得访问报告,并返回给用户 /// </summary> /// <param name="a"></param> void Web_AfterConnectionGetReportAndSendToUser(object a) { System.Net.Sockets.TcpClient socketcomein = a as System.Net.Sockets.TcpClient; if (socketcomein == null) { LogInToEvent.WriteError("未知错误:socketcomein == null"); return; } try { var stream = socketcomein.GetStream(); System.IO.StreamReader rstream = new System.IO.StreamReader(stream); string i = rstream.ReadLine(); var where = i.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries); if (! (where.Length == 3 && where[1].Trim().StartsWith("/")) ) { string errorMessage = "请求格式错误,请发送 GET / HTTP1.1 \n" + i; foreach (var p in where) { errorMessage += "\n" + p + "\n"; } var error_gs = System.Text.Encoding.UTF8.GetBytes(errorMessage); stream.Write(error_gs, 0, error_gs.Length); stream.Close(); socketcomein.Close(); return; } string report = Web_GetReport(where[1]); string head = "http/1.1 200 ok\n" + "Content-Type: text/html\n"; byte[] content = System.Text.Encoding.UTF8.GetBytes(report); head += "Content-Length:" + content.Length + "\n\n"; var headstr = System.Text.Encoding.UTF8.GetBytes(head); stream.Write(headstr, 0, headstr.Length); stream.Write(content, 0, content.Length); stream.Close(); socketcomein.Close(); } catch (Exception e) { LogInToEvent.WriteError(e.ToString()); return; } }
public static void SendTCP(string host, int port, string msg) { System.Net.Sockets.TcpClient tcp; try { tcp = new System.Net.Sockets.TcpClient(host, port); } catch { return; } try { System.Net.Sockets.NetworkStream ns = tcp.GetStream(); try { ns.ReadTimeout = 10000; ns.WriteTimeout = 10000; Encoding enc = Encoding.UTF8; byte[] sendBytes = enc.GetBytes(msg + '\n'); ns.Write(sendBytes, 0, sendBytes.Length); } finally { ns.Close(); } } finally { tcp.Close(); } }
public void StartForTestOnly(int port, System.Threading.CancellationToken token) { _udpThread = new System.Threading.Thread(() => _udpReceiver.ReceiveStuff(token)); _udpThread.Start(); System.Net.Sockets.TcpListener serverSocket = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Any, port); SocketEventInfo?.Invoke("Listening"); System.Net.Sockets.TcpClient clientSocket = default(System.Net.Sockets.TcpClient); int clientId = 0; serverSocket.Start(); clientId = 0; while (!token.IsCancellationRequested) { clientId += 1; clientSocket = serverSocket.AcceptTcpClient(); _log.Debug($"New TCP Client connected"); System.Threading.Thread thread = new System.Threading.Thread(() => StartServerMessengerForTest(clientSocket, clientId, token)); thread.Start(); } clientSocket.Close(); serverSocket.Stop(); SocketEventInfo?.Invoke("Closed"); }
public bool updateWebStatus() { string currentImg; try { if (string.IsNullOrEmpty(_publicDns) == false) { System.Net.Sockets.TcpClient clnt = new System.Net.Sockets.TcpClient(_publicDns, 80); clnt.Close(); currentImg = "images/ServerRunning.png"; } else { currentImg = "images/ServerStopped.png"; } } catch (System.Exception) { currentImg = "images/ServerStopped.png"; } if (string.Compare(img, currentImg) == 0) { return(false); } else { img = currentImg; return(true); } }
public bool sendData(string adr, int port, byte[] donnees, int timeout) { System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient(); System.Net.Sockets.NetworkStream ns = null; try { client.Connect(adr, port); if (!client.Connected) { throw new Exception("Pas de connexion"); } client.SendTimeout = timeout; ns = client.GetStream(); ns.Write(donnees, 0, donnees.Length); return(true); } catch { } finally { if (ns != null) { ns.Close(); } client.Close(); } return(false); }
private void ThreadRun() { Byte [] abData = new Byte[m_nBufferSize]; try { int nReceived = m_theSocket.GetStream().Read(abData, 0, m_nBufferSize); while (nReceived > 0) { m_theCommands.Process(abData); nReceived = m_theSocket.GetStream().Read(abData, 0, m_nBufferSize); } } catch (System.Net.Sockets.SocketException) { } catch (System.IO.IOException) { } FtpServerMessageHandler.SendMessage(m_nId, "Connection closed"); if (Closed != null) { Closed(this); } m_theSocket.Close(); }
private void TCPIP(String ZPLString) { string ipAddress = txtip.Text; // Printer IP Address and communication port int port = 9100; try { // Open connection System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient(); client.Connect(ipAddress, port); // Write ZPL String to connection System.IO.StreamWriter writer = new System.IO.StreamWriter(client.GetStream()); writer.Write(ZPLString); writer.Flush(); // Close Connection writer.Close(); client.Close(); } catch (Exception ex) { // Catch Exception } } //tcpip
public bool IsConnectedToInternet() { /* WebClient client = new WebClient(); * string host = "www.google.com"; * bool result = false; * Ping p = new Ping(); * try * { * PingReply reply = p.Send(host, 3000); * if (reply.Status == IPStatus.Success) * return true; * } * catch { } * return result;*/ try { System.Net.Sockets.TcpClient clnt = new System.Net.Sockets.TcpClient("www.google.com", 80); clnt.Close(); return(true); } catch (System.Exception) { return(false); } }
public void process() { // we can't use a StreamReader for input, because it buffers up extra data on us inside it's // "processed" view of the world, and we want the data raw after the headers inputByteStream = new System.IO.BufferedStream(socket.GetStream()); // we probably shouldn't be using a streamwriter for all output from handlers either outputStream = new System.IO.StreamWriter(new System.IO.BufferedStream(socket.GetStream())); outputByteStream = new System.IO.BufferedStream(socket.GetStream()); try { parseRequest(); if (http_method.Equals("GET")) { handleGETRequest(); } else if (http_method.Equals("POST")) { handlePOSTRequest(); } } catch (Exception e) { Console.WriteLine("Exception: " + e.ToString()); writeFailure(); } //outputStream.Flush(); // bs.Flush(); // flush any remaining output inputByteStream = null; outputStream = null; // bs = null; socket.Close(); }
private void TryToConnect(object state) { string strip = state.ToString(); try { System.Net.Sockets.TcpClient tc = new System.Net.Sockets.TcpClient(strip, 8080); if (tc.Connected) { tc.Close(); if (!allServers.Contains(strip)) { allServers.Add(strip); } } } catch { if (allServers.Contains(strip)) { allServers.Remove(strip); } } finally { this.Invoke((MethodInvoker) delegate { this.Text = allServers.Count + " server(s) found."; }); } }
private void CloseConn() { #if DEBUG Console.WriteLine("关闭连接..."); #endif try { if (client != null) { RLib.WatchLog.Loger.Log("正在关闭tcp!", ""); if (client.Connected) { client.Close(); } #if DEBUG Console.WriteLine("关闭连接 成功"); #endif } } finally { #if DEBUG Console.WriteLine("关闭连接完结束"); #endif client = null; stream = null; this.lastping = null; LastReceived.Clear(); } }
private object sendAndReceivedData(string adr, int port, byte[] donnees, int timeout) { System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient(); System.Net.Sockets.NetworkStream ns = null; try { client.Connect(adr, port); if (!client.Connected) { throw new Exception("Pas de connexion"); } client.SendTimeout = timeout; client.ReceiveTimeout = timeout; ns = client.GetStream(); ns.Write(donnees, 0, donnees.Length); byte[] data = new byte[client.ReceiveBufferSize]; return(ns.Read(data, 0, client.ReceiveBufferSize)); } catch { } finally { if (ns != null) { ns.Close(); } client.Close(); } return(null); }
private static System.Net.Sockets.TcpClient Connect(string addr, int port) { TimeoutObject.Reset(); socketexception = null; System.Net.Sockets.TcpClient tcpclient = new System.Net.Sockets.TcpClient(); tcpclient.BeginConnect(addr, port, new AsyncCallback(ConnectCallback), tcpclient); if (TimeoutObject.WaitOne(TimeSpan.FromMilliseconds(200), false)) { if (IsConnectionSuccessful) { return(tcpclient); } else { throw socketexception; } } else { tcpclient.Close(); throw new TimeoutException("Timeout Exception"); } }
///// <summary> ///// 操作系统的登录用户名 ///// </summary> ///// <returns>系统的登录用户名</returns> //public static string GetUserName() //{ // try // { // string strUserName = string.Empty; // ManagementClass mc = new ManagementClass("Win32_ComputerSystem"); // ManagementObjectCollection moc = mc.GetInstances(); // foreach (ManagementObject mo in moc) // { // strUserName = mo["UserName"].ToString(); // } // moc = null; // mc = null; // return strUserName; // } // catch // { // return "unknown"; // } //} ///// <summary> ///// 获取本机MAC地址 ///// </summary> ///// <returns>本机MAC地址</returns> //public static string GetMacAddress() //{ // try // { // string strMac = string.Empty; // ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration"); // ManagementObjectCollection moc = mc.GetInstances(); // foreach (ManagementObject mo in moc) // { // if ((bool)mo["IPEnabled"] == true) // { // strMac = mo["MacAddress"].ToString(); // } // } // moc = null; // mc = null; // return strMac; // } // catch // { // return "unknown"; // } //} ///// <summary> ///// 获取本机的物理地址 ///// </summary> ///// <returns></returns> //public static string getMacAddr_Local() //{ // string madAddr = null; // try // { // ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration"); // ManagementObjectCollection moc2 = mc.GetInstances(); // foreach (ManagementObject mo in moc2) // { // if (Convert.ToBoolean(mo["IPEnabled"]) == true) // { // madAddr = mo["MacAddress"].ToString(); // madAddr = madAddr.Replace(':', '-'); // } // mo.Dispose(); // } // if (madAddr == null) // { // return "unknown"; // } // else // { // return madAddr; // } // } // catch (Exception) // { // return "unknown"; // } //} ///// <summary> ///// 获取客户端内网IPv6地址 ///// </summary> ///// <returns>客户端内网IPv6地址</returns> //public static string GetClientLocalIPv6Address() //{ // string strLocalIP = string.Empty; // try // { // IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName()); // IPAddress ipAddress = ipHost.AddressList[0]; // strLocalIP = ipAddress.ToString(); // return strLocalIP; // } // catch // { // return "unknown"; // } //} ///// <summary> ///// 获取客户端内网IPv4地址 ///// </summary> ///// <returns>客户端内网IPv4地址</returns> //public static string GetClientLocalIPv4Address() //{ // string strLocalIP = string.Empty; // try // { // IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName()); // IPAddress ipAddress = ipHost.AddressList[0]; // strLocalIP = ipAddress.ToString(); // return strLocalIP; // } // catch // { // return "unknown"; // } //} ///// <summary> ///// 获取客户端内网IPv4地址集合 ///// </summary> ///// <returns>返回客户端内网IPv4地址集合</returns> //public static List<string> GetClientLocalIPv4AddressList() //{ // List<string> ipAddressList = new List<string>(); // try // { // IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName()); // foreach (IPAddress ipAddress in ipHost.AddressList) // { // if (!ipAddressList.Contains(ipAddress.ToString())) // { // ipAddressList.Add(ipAddress.ToString()); // } // } // } // catch // { // } // return ipAddressList; //} ///// <summary> ///// 获取客户端外网IP地址 ///// </summary> ///// <returns>客户端外网IP地址</returns> //public static string GetClientInternetIPAddress() //{ // string strInternetIPAddress = string.Empty; // try // { // using (WebClient webClient = new WebClient()) // { // strInternetIPAddress = webClient.DownloadString("http://www.coridc.com/ip"); // Regex r = new Regex("[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}"); // Match mth = r.Match(strInternetIPAddress); // if (!mth.Success) // { // strInternetIPAddress = GetClientInternetIPAddress2(); // mth = r.Match(strInternetIPAddress); // if (!mth.Success) // { // strInternetIPAddress = "unknown"; // } // } // return strInternetIPAddress; // } // } // catch // { // return "unknown"; // } //} ///// <summary> ///// 获取本机公网IP地址 ///// </summary> ///// <returns>本机公网IP地址</returns> //private static string GetClientInternetIPAddress2() //{ // string tempip = ""; // try // { // //http://iframe.ip138.com/ic.asp 返回的是:您的IP是:[220.231.17.99] 来自:北京市 光环新网 // WebRequest wr = WebRequest.Create("http://iframe.ip138.com/ic.asp"); // Stream s = wr.GetResponse().GetResponseStream(); // StreamReader sr = new StreamReader(s, Encoding.Default); // string all = sr.ReadToEnd(); //读取网站的数据 // int start = all.IndexOf("[") + 1; // int end = all.IndexOf("]", start); // tempip = all.Substring(start, end - start); // sr.Close(); // sr.Dispose(); // s.Close(); // s.Dispose(); // return tempip; // } // catch // { // return "unknown"; // } //} ///// <summary> ///// 获取硬盘序号 ///// </summary> ///// <returns>硬盘序号</returns> //public static string GetDiskID() //{ // try // { // string strDiskID = string.Empty; // ManagementClass mc = new ManagementClass("Win32_DiskDrive"); // ManagementObjectCollection moc = mc.GetInstances(); // foreach (ManagementObject mo in moc) // { // strDiskID = mo.Properties["Model"].Value.ToString(); // } // moc = null; // mc = null; // return strDiskID; // } // catch // { // return "unknown"; // } //} ///// <summary> ///// 获取CpuID ///// </summary> ///// <returns>CpuID</returns> //public static string GetCpuID() //{ // try // { // string strCpuID = string.Empty; // ManagementClass mc = new ManagementClass("Win32_Processor"); // ManagementObjectCollection moc = mc.GetInstances(); // foreach (ManagementObject mo in moc) // { // strCpuID = mo.Properties["ProcessorId"].Value.ToString(); // } // moc = null; // mc = null; // return strCpuID; // } // catch // { // return "unknown"; // } //} ///// <summary> ///// 获取操作系统类型 ///// </summary> ///// <returns>操作系统类型</returns> //public static string GetSystemType() //{ // try // { // string strSystemType = string.Empty; // ManagementClass mc = new ManagementClass("Win32_ComputerSystem"); // ManagementObjectCollection moc = mc.GetInstances(); // foreach (ManagementObject mo in moc) // { // strSystemType = mo["SystemType"].ToString(); // } // moc = null; // mc = null; // return strSystemType; // } // catch // { // return "unknown"; // } //} ///// <summary> ///// 获取操作系统名称 ///// </summary> ///// <returns>操作系统名称</returns> //public static string GetSystemName() //{ // try // { // string strSystemName = string.Empty; // ManagementObjectSearcher mos = new ManagementObjectSearcher("root\\CIMV2", "SELECT PartComponent FROM Win32_SystemOperatingSystem"); // foreach (ManagementObject mo in mos.Get()) // { // strSystemName = mo["PartComponent"].ToString(); // } // mos = new ManagementObjectSearcher("root\\CIMV2", "SELECT Caption FROM Win32_OperatingSystem"); // foreach (ManagementObject mo in mos.Get()) // { // strSystemName = mo["Caption"].ToString(); // } // return strSystemName; // } // catch // { // return "unknown"; // } //} ///// <summary> ///// 获取物理内存信息 ///// </summary> ///// <returns>物理内存信息</returns> //public static string GetTotalPhysicalMemory() //{ // try // { // string strTotalPhysicalMemory = string.Empty; // ManagementClass mc = new ManagementClass("Win32_ComputerSystem"); // ManagementObjectCollection moc = mc.GetInstances(); // foreach (ManagementObject mo in moc) // { // strTotalPhysicalMemory = mo["TotalPhysicalMemory"].ToString(); // } // moc = null; // mc = null; // return strTotalPhysicalMemory; // } // catch // { // return "unknown"; // } //} ///// <summary> ///// 获取主板id ///// </summary> ///// <returns></returns> //public static string GetMotherBoardID() //{ // try // { // ManagementClass mc = new ManagementClass("Win32_BaseBoard"); // ManagementObjectCollection moc = mc.GetInstances(); // string strID = null; // foreach (ManagementObject mo in moc) // { // strID = mo.Properties["SerialNumber"].Value.ToString(); // break; // } // return strID; // } // catch // { // return "unknown"; // } //} ///// <summary> ///// 获取公用桌面路径 ///// </summary> //public static string GetAllUsersDesktopFolderPath() //{ // RegistryKey folders; // folders = OpenRegistryPath(Registry.LocalMachine, @"/software/microsoft/windows/currentversion/explorer/shell folders"); // string desktopPath = folders.GetValue("Common Desktop").ToString(); // return desktopPath; //} ///// <summary> ///// 获取公用启动项路径 ///// </summary> //public static string GetAllUsersStartupFolderPath() //{ // RegistryKey folders; // folders = OpenRegistryPath(Registry.LocalMachine, @"/software/microsoft/windows/currentversion/explorer/shell folders"); // string Startup = folders.GetValue("Common Startup").ToString(); // return Startup; //} //private static RegistryKey OpenRegistryPath(RegistryKey root, string s) //{ // s = s.Remove(0, 1) + @"/"; // while (s.IndexOf(@"/") != -1) // { // root = root.OpenSubKey(s.Substring(0, s.IndexOf(@"/"))); // s = s.Remove(0, s.IndexOf(@"/") + 1); // } // return root; //} #endregion /// <summary> /// 获取当前使用的IP /// </summary> /// <returns></returns> public static string GetLocalIP() { string result = RunApp("route", "print", true); Match m = Regex.Match(result, @"0.0.0.0\s+0.0.0.0\s+(\d+.\d+.\d+.\d+)\s+(\d+.\d+.\d+.\d+)"); if (m.Success) { return(m.Groups[2].Value); } else { try { System.Net.Sockets.TcpClient c = new System.Net.Sockets.TcpClient(); c.Connect("www.baidu.com", 80); string ip = ((System.Net.IPEndPoint)c.Client.LocalEndPoint).Address.ToString(); c.Close(); return(ip); } catch (Exception) { return(null); } } }
private void button_get_ip_Click(object sender, EventArgs e) { //获取IP地址 string result = ("route"); Match m = Regex.Match(result, @"0.0.0.0\s+0.0.0.0\s+(\d+.\d+.\d+.\d+)\s+(\d+.\d+.\d+.\d+)"); if (m.Success) { richTextBox_authinfo.Text = m.Groups[2].Value; } else { try { System.Net.Sockets.TcpClient c = new System.Net.Sockets.TcpClient(); c.Connect("www.baidu.com", 80); string ip = ((System.Net.IPEndPoint)c.Client.LocalEndPoint).Address.ToString(); c.Close(); textBox_ip.Text = ip; } catch (Exception) { textBox_ip.Text = "请检查网络连接"; } } }
public void Dispose() { logger.a("dispose called"); enc.FIXME_kbps = -1; stdin = stdout = null; crashed = true; try { logger.a("proc dispose"); proc.Kill(); } catch { logger.a("proc dispose failure"); // how can you kill that which is already dead } try { logger.a("socket dispose"); tc.Close(); } catch { logger.a("socket dispose failure"); // you took a nuke to the head and you're worrying about a socket? } }
private int SendToPrinter() { try { // Open connection System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient(); client.Connect(e.PrinterIpAddress, Port); // Write ZPL String to connection System.IO.StreamWriter writer = new System.IO.StreamWriter(client.GetStream()); writer.Write(e.PrintCode); writer.Flush(); // Close Connection writer.Close(); client.Close(); return(0); } catch (Exception ex) { if (Logger.Enabled) { Logger.Log(ex.ToString()); } return(3); } }
private async Task <bool> PingHost(IPEndPoint target, Guid remote_session_id, CancellationToken cancel_token) { Logger.Debug("Ping requested. Try to ping: {0}({1})", target, remote_session_id); bool result = false; try { var client = new System.Net.Sockets.TcpClient(target.AddressFamily); client.ReceiveTimeout = 2000; client.SendTimeout = 2000; await client.ConnectAsync(target.Address, target.Port).ConfigureAwait(false); var stream = client.GetStream(); await stream.WriteAsync(new Atom(Atom.PCP_CONNECT, 1), cancel_token).ConfigureAwait(false); var helo = new AtomCollection(); helo.SetHeloSessionID(PeerCast.SessionID); await stream.WriteAsync(new Atom(Atom.PCP_HELO, helo), cancel_token).ConfigureAwait(false); var res = await stream.ReadAtomAsync(cancel_token).ConfigureAwait(false); if (res.Name == Atom.PCP_OLEH) { var session_id = res.Children.GetHeloSessionID(); if (session_id.HasValue && session_id.Value == remote_session_id) { Logger.Debug("Ping succeeded"); result = true; } else { Logger.Debug("Ping failed. Remote SessionID mismatched"); } } await stream.WriteAsync(new Atom(Atom.PCP_QUIT, Atom.PCP_ERROR_QUIT), cancel_token).ConfigureAwait(false); stream.Close(); client.Close(); } catch (InvalidDataException e) { Logger.Debug("Ping failed"); Logger.Debug(e); } catch (System.Net.Sockets.SocketException e) { Logger.Debug("Ping failed"); Logger.Debug(e); } catch (EndOfStreamException e) { Logger.Debug("Ping failed"); Logger.Debug(e); } catch (System.IO.IOException io_error) { Logger.Debug("Ping failed"); Logger.Debug(io_error); if (!(io_error.InnerException is System.Net.Sockets.SocketException)) { throw; } } return(result); }
public static bool CheckPort(string ip, int port, int timeout) { using (System.Net.Sockets.TcpClient tcp = new System.Net.Sockets.TcpClient()) { IAsyncResult ar = tcp.BeginConnect(ip, port, null, null); System.Threading.WaitHandle wh = ar.AsyncWaitHandle; try { if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromMilliseconds(timeout), false)) { tcp.Close(); throw new TimeoutException(); } tcp.EndConnect(ar); return true; } catch (Exception) { return false; } finally { wh.Close(); } } }
private void printButton_Click(object sender, EventArgs e) { // Printer IP Address and communication port string ipAddress = printerIpText.Text; int port = 9100; try { // Open connection System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient(); client.Connect(ipAddress, port); // Write ZPL String to connection System.IO.StreamWriter writer = new System.IO.StreamWriter(client.GetStream()); writer.Write(zplCode); writer.Flush(); // Close Connection writer.Close(); client.Close(); MessageBox.Show("Print Successful!", "Success"); this.Close(); } catch (Exception ex) { Console.WriteLine("Error: {0}", ex); MessageBox.Show("No printer installed corresponds to the IP address given", "No response"); } }
public void TryPrint(string zplCommands) { try { // Open connection System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient(); client.Connect(this.m_IPAddress, this.m_Port); // Write ZPL String to connection System.IO.StreamWriter writer = new System.IO.StreamWriter(client.GetStream()); writer.Write(zplCommands); writer.Flush(); // Close Connection writer.Close(); client.Close(); } catch (Exception ex) { this.m_ErrorCount += 1; if (this.m_ErrorCount < 10) { System.Threading.Thread.Sleep(5000); this.TryPrint(zplCommands); } else { throw ex; } } }
private bool CheckConnection() { bool success = false; string ip = ConfigurationManager.AppSettings["bankServerIP"]; int port = Convert.ToInt32(ConfigurationManager.AppSettings["bankServerPort"]); int timeout = Convert.ToInt32(ConfigurationManager.AppSettings["connectionTimeout"]); try { using (System.Net.Sockets.TcpClient tcp = new System.Net.Sockets.TcpClient()) { IAsyncResult ar = tcp.BeginConnect(ip, port, null, null); System.Threading.WaitHandle wh = ar.AsyncWaitHandle; try { if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(timeout), false)) { tcp.Close(); throw new TimeoutException(); } success = tcp.Connected; tcp.EndConnect(ar); } finally { wh.Close(); } } } catch (Exception e) { log.Error(e); } return(success); }
// Close connection when things have gone wrong... void close() { // System.out.println("Closing Connection..."); try { sendTime = -1L; if (output != null) { output.close(); output = null; } if (input != null) { input.Close(); input = null; } if (connection != null) { connection.Close(); connection = null; } } catch (Exception e) { if (PrologSession.debugging()) { PrologSession.WriteStackTrace(e, Console.Error); } } }
private string strConectaServidorSMTP() { string strRetorno = "OK", strMensagem; m_tcpClient = new System.Net.Sockets.TcpClient(); try { // Connecta ao servidor SMPT m_tcpClient.Connect(m_strSMTP, m_nPortSmpt); } catch { return("CErro: Servidor SMTP inválido ou Porta SMTP errada."); } // Conseguiu conexão, seta netStream, canal de comunicação m_netStream = m_tcpClient.GetStream(); if (m_netStream == null) { return("CErro: Não foi possível adquirir o canal de comunicação."); } // RESPOSTA strMensagem = strAdquireResposta(); if (strMensagem.Substring(0, 3) != "220") { if (m_tcpClient != null) { m_tcpClient.Close(); m_tcpClient = null; return("SErro: Problema ao receber informacoes do servidor."); } } return(strRetorno); }
static void Main(string[] args) { try { XmlConfigurator.Configure(); if (!args.Any()) { throw new Exception("Program został wystartowany bez argumentu"); } var port = Settings.Default.Port; var host = Settings.Default.IpAddress; var client = new System.Net.Sockets.TcpClient(host, port); var data = Encoding.ASCII.GetBytes(args[0]); var stream = client.GetStream(); stream.Write(data, 0, data.Length); stream.Close(); client.Close(); } catch (Exception ex) { if (Settings.Default.LoggingEnable) { Log.Error(ex.Message); if (ex.InnerException != null) { Log.Error(ex.InnerException.Message); } } } }
/// <summary> /// Called from a job thread to handle HTTP request /// </summary> protected void HandleClient(ref object argument) { byte[] buffer = new byte[1024]; System.Net.Sockets.TcpClient tcpClient = (System.Net.Sockets.TcpClient)argument; bool stream = false; try { System.Net.Sockets.NetworkStream networkStream = tcpClient.GetStream(); int result = networkStream.Read(buffer, 0, buffer.Length); if (result > 0) { Http.statistics.incomingBytes += result; // convert bytes to string string request = Encoding.ASCII.GetString(buffer, 0, result); ProcessRequest(rootPath, networkStream, request, ref stream); } // close the client socket tcpClient.Close(); } catch (Exception e) { System.Console.WriteLine(e.Message); System.Console.WriteLine(e.StackTrace); } }
// // // void sendzpl() { // Printer IP Address and communication port const string ipAddress = "192.168.2.216"; const int port = 9100; // ZPL Command(s) string ZPLString = "^XA^FO50,5^B3N,N,50,N,N^FD" + barcode + "^FS^FO50,70^ADN,28,20^FD" + barcode + "^FS^XZ"; try { // Open connection System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient(); client.Connect(ipAddress, port); // Write ZPL String to connection System.IO.StreamWriter writer = new System.IO.StreamWriter(client.GetStream()); writer.Write(ZPLString); writer.Flush(); // Close Connection writer.Close(); client.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error"); // Catch Exception } }
public static string GetLocalIP() { string result = RunApp("route", "print", true); System.Text.RegularExpressions.Match match = System.Text.RegularExpressions.Regex.Match(result, @"0.0.0.0\s+0.0.0.0\s+(\d+.\d+.\d+.\d+)\s+(\d+.\d+.\d+.\d+)"); if (match.Success) { return(match.Groups[2].Value); } else { try { System.Net.Sockets.TcpClient cli = new System.Net.Sockets.TcpClient(); cli.Connect(conndomain, 80); string ip = ((System.Net.IPEndPoint)cli.Client.LocalEndPoint).Address.ToString(); cli.Close(); return(ip); } catch (Exception) { return(null); } } }
public void checkAvailability(object sender, System.ComponentModel.DoWorkEventArgs e) { try { System.Net.Sockets.TcpClient clnt = new System.Net.Sockets.TcpClient("smtp.gmail.com", 587); clnt.Close(); e.Result = EmailResponse.ServerReachable; } catch { e.Result = EmailResponse.ServerUnreachable; } }
private void checkAvailability(object sender, System.ComponentModel.DoWorkEventArgs e) { try { System.Net.Sockets.TcpClient clnt=new System.Net.Sockets.TcpClient("smtp.gmail.com",587); clnt.Close(); email_available = true; } catch { email_available = false; } }
public static string PerformWhois(string WhoisServerHost, int WhoisServerPort, string Host) { string result=""; try { String strDomain = Host; char[] chSplit = {'.'}; string[] arrDomain = strDomain.Split(chSplit); // There may only be exactly one domain name and one suffix if (arrDomain.Length != 2) { return ""; } // The suffix may only be 2 or 3 characters long int nLength = arrDomain[1].Length; if (nLength != 2 && nLength != 3) { return ""; } System.Collections.Hashtable table = new System.Collections.Hashtable(); table.Add("de", "whois.denic.de"); table.Add("be", "whois.dns.be"); table.Add("gov", "whois.nic.gov"); table.Add("mil", "whois.nic.mil"); String strServer = WhoisServerHost; if (table.ContainsKey(arrDomain[1])) { strServer = table[arrDomain[1]].ToString(); } else if (nLength == 2) { // 2-letter TLD's always default to RIPE in Europe strServer = "whois.ripe.net"; } System.Net.Sockets.TcpClient tcpc = new System.Net.Sockets.TcpClient (); tcpc.Connect(strServer, WhoisServerPort); String strDomain1 = Host+"\r\n"; Byte[] arrDomain1 = System.Text.Encoding.ASCII.GetBytes(strDomain1.ToCharArray()); System.IO.Stream s = tcpc.GetStream(); s.Write(arrDomain1, 0, strDomain1.Length); System.IO.StreamReader sr = new System.IO.StreamReader(tcpc.GetStream(), System.Text.Encoding.ASCII); System.Text.StringBuilder strBuilder = new System.Text.StringBuilder(); string strLine = null; while (null != (strLine = sr.ReadLine())) { strBuilder.Append(strLine+"\r\n"); } result = strBuilder.ToString(); tcpc.Close(); }catch(Exception exc) { result="Could not connect to WHOIS server!\r\n"+exc.ToString(); } return result; }
//--簡單檢查連線狀況 public static bool ConnectionExists() { try { System.Net.Sockets.TcpClient clnt = new System.Net.Sockets.TcpClient("mis.twse.com.tw", 80); clnt.Close(); return true; } catch //(System.Exception ex) { return false; } }
private void SendBytes(IPEndPoint endpoint, byte[] buffer) { using (var client = new System.Net.Sockets.TcpClient()) { client.Connect(endpoint); var stream = client.GetStream(); stream.Write(buffer, 0, buffer.Length); stream.Flush(); client.Close(); } }
static void _main() { BlackCore.basic.cParams args = bcore.app.args; client = new System.Net.Sockets.TcpClient(); int wavInDevices = WaveIn.DeviceCount; int selWav = 0; for (int wavDevice = 0; wavDevice < wavInDevices; wavDevice++) { WaveInCapabilities deviceInfo = WaveIn.GetCapabilities(wavDevice); Console.WriteLine("Device {0}: {1}, {2} channels", wavDevice, deviceInfo.ProductName, deviceInfo.Channels); } Console.Write("Select device: "); selWav = int.Parse(Console.ReadLine()); Console.WriteLine("Selected device is " + selWav.ToString()); sshClient = new SshClient(args["host"], args["user"], args["pass"]); sshClient.Connect(); if (sshClient.IsConnected) { shell = sshClient.CreateShellStream("xterm", 50, 50, 640, 480, 17640); Console.WriteLine("Open listening socket..."); shell.WriteLine("nc -l " + args["port"] + "|pacat --playback"); System.Threading.Thread.Sleep(2000); Console.WriteLine("Try to connect..."); client.Connect(args["host"], int.Parse(args["port"])); if (!client.Connected) return; upStream = client.GetStream(); //==================== WaveInEvent wavInStream = new WaveInEvent(); wavInStream.DataAvailable += new EventHandler<WaveInEventArgs>(wavInStream_DataAvailable); wavInStream.DeviceNumber = selWav; wavInStream.WaveFormat = new WaveFormat(44100, 16, 2); wavInStream.StartRecording(); Console.WriteLine("Working....."); Console.ReadKey(); sshClient.Disconnect(); client.Close(); wavInStream.StopRecording(); wavInStream.Dispose(); wavInStream = null; } }
public static bool TcpSocketTest(string websiteUrl) { try { System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient(websiteUrl, 80); client.Close(); return true; } catch (System.Exception ex) { return false; } }
//public ActionResult ListUpnp() //{ // var upnp = new NATUPNPLib.UPnPNATClass(); // if (upnp.StaticPortMappingCollection == null) return Content("UPnP Disabled"); // var result = upnp.StaticPortMappingCollection.Cast<NATUPNPLib.IStaticPortMapping>() // .Aggregate("", (s, m) => s + m.Description + "<br/>"); // return Content(result); //} //public ActionResult EnableUpnp() //{ // var upnp = new NATUPNPLib.UPnPNATClass(); // if (upnp.StaticPortMappingCollection == null) return Content("UPnP Disabled"); // var localIP = System.Net.Dns.GetHostAddresses(System.Net.Dns.GetHostName()) // .First(ip => ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork); // upnp.StaticPortMappingCollection.Add(25565, "TCP", 25565, localIP.ToString(), true, "Minecraft"); // return Redirect("/Home/ListUpnp"); //} //public ActionResult DisableUpnp() //{ // var upnp = new NATUPNPLib.UPnPNATClass(); // if (upnp.StaticPortMappingCollection == null) return Content("UPnP Disabled"); // upnp.StaticPortMappingCollection.Remove(25565, "TCP"); // return Redirect("/Home/ListUpnp"); //} public ActionResult Test() { var client = new System.Net.Sockets.TcpClient(); try { client.Connect("localhost", 25565); client.Close(); return Content("Connection OK " + DateTime.Now.Ticks); } catch (Exception e) { return Content("Error:<br />" + e.Message); } }
private bool checkInternetConnection() { try { System.Net.Sockets.TcpClient clnt = new System.Net.Sockets.TcpClient("developer.anscamobile.com", 80); clnt.Close(); return true; } catch (Exception ex) { return false; // host not reachable. } }
public void Scan(object data) { System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient(); try { client.BeginConnect(this.IPAddress, this.Port, new AsyncCallback(AttemptConnect), client); int x = 0; while (x <= Settings.PortScanTimeoutSeconds) { System.Threading.Thread.Sleep(1000); x++; } client.Close(); } catch (Exception e) { Terminals.Logging.Log.Info("", e); } }
public static void SendRaw(string Hostname, int TunnelPort, System.IO.Stream ClientStream) { System.Net.Sockets.TcpClient tunnelClient = new System.Net.Sockets.TcpClient(Hostname, TunnelPort); var tunnelStream = tunnelClient.GetStream(); var tunnelReadBuffer = new byte[BUFFER_SIZE]; Task sendRelay = new Task(() => StreamHelper.CopyTo(ClientStream, tunnelStream, BUFFER_SIZE)); Task receiveRelay = new Task(() => StreamHelper.CopyTo(tunnelStream, ClientStream, BUFFER_SIZE)); sendRelay.Start(); receiveRelay.Start(); Task.WaitAll(sendRelay, receiveRelay); if (tunnelStream != null) tunnelStream.Close(); if (tunnelClient != null) tunnelClient.Close(); }
private void Verify(sbyte message) { try { System.Net.Sockets.TcpClient s = new System.Net.Sockets.TcpClient(Enclosing_Instance.host, Enclosing_Instance.port); System.IO.Stream out_Renamed = s.GetStream(); out_Renamed.WriteByte((byte) Enclosing_Instance.id); out_Renamed.WriteByte((byte) message); System.IO.Stream in_Renamed = s.GetStream(); int result = in_Renamed.ReadByte(); in_Renamed.Close(); out_Renamed.Close(); s.Close(); if (result != 0) throw new System.SystemException("lock was double acquired"); } catch (System.Exception e) { throw new System.SystemException(e.Message, e); } }
public string Connect() { CQ = new CommandQueue(); if (this.online) { // Networking shit try { TC = new System.Net.Sockets.TcpClient(); //TC.Connect("169.254.19.75", 3000); IAsyncResult result = TC.BeginConnect("169.254.67.42", 3000, null, null); if (!result.AsyncWaitHandle.WaitOne(8000, true)) // 4 sec timout { TC.Close(); throw new Exception(); } SW = new StreamWriter(TC.GetStream()); //request dwarf count from server //SW.WriteLine("add dwarf"); //SW.Flush(); StreamReader SR = new StreamReader(TC.GetStream()); string name = SR.ReadLine(); t = new Thread(new ParameterizedThreadStart(runListener)); t.Start(CQ); return name; } catch (Exception e) { this.online = false; } return "error"; } else { return "0"; } }
public string ConnectRemocon(string ip, string send){ string res = ip; string ipOrHost = ip; string sendMsg = send; int port = 51013; System.Net.Sockets.TcpClient tcp = new System.Net.Sockets.TcpClient(ipOrHost, port); System.Net.Sockets.NetworkStream ns = tcp.GetStream(); ns.ReadTimeout = 10000; ns.WriteTimeout = 10000; System.Text.Encoding enc = System.Text.Encoding.UTF8; byte[] sendBytes = enc.GetBytes(sendMsg+"\r\n"); ns.Write(sendBytes, 0, sendBytes.Length); System.IO.MemoryStream ms = new System.IO.MemoryStream(); byte[] resBytes = new byte[256]; int resSize = 0; do { resSize = ns.Read(resBytes, 0, resBytes.Length); if (resSize == 0) { break; } ms.Write(resBytes, 0, resSize); } while (ns.DataAvailable || resBytes[resSize - 1] != '\n'); string resMsg1 = enc.GetString(ms.GetBuffer(), 0, (int)ms.Length); ms.Close(); resMsg1 = resMsg1.TrimEnd('\n'); resMsg1 = resMsg1.TrimEnd('\r'); ns.Close(); tcp.Close(); return resMsg1; }
/** 別のプログラムと通信するための処理 */ private void run() { //サーバーのホスト名とポート番号 string host = "localhost"; int port = 50001; //TcpClientを作成し、サーバーと接続する tcp = new System.Net.Sockets.TcpClient(host, port); //NetworkStreamを取得する ns = tcp.GetStream(); Debug.Log("接続を開始します."); while (!terminate) { //受信したデータを文字列に変換 string resMsg = "none"; //サーバーから送られたデータを受信する System.IO.MemoryStream ms = new System.IO.MemoryStream(); byte[] resBytes = new byte[256]; do { //データの一部を受信する int resSize = ns.Read(resBytes, 0, resBytes.Length); //Readが0を返した時はサーバーが切断したと判断 if (resSize == 0) { Debug.Log("サーバから切断されました."); break; } //受信したデータを蓄積する ms.Write(resBytes, 0, resSize); } while (ns.DataAvailable); //文字列をByte型配列に変換 System.Text.Encoding enc = System.Text.Encoding.UTF8; resMsg = enc.GetString(ms.ToArray()); ms.Close(); lock (data) { data = resMsg; } Debug.Log(data); } //閉じる ns.Close(); tcp.Close(); Debug.Log("Thread を終了します."); }
private void ScanPorts() { System.Net.Sockets.TcpClient tcpSock; int tPort; do // while (currPort < endPort) { nCurrPort++; // increment nCurrPort by 1 tPort = nCurrPort; // Thread Port : saves ports to probe in the routeins local variable - less chances of two or more threads getting the same port number try { tcpSock = new System.Net.Sockets.TcpClient(); tcpSock.Connect(cCurrIP, tPort); // Attempt to connect to an IP on a Port System.Threading.Thread.Sleep(nTimeOut); if (tcpSock.Connected) { WriteToList(cCurrIP + ":" + tPort); // add open ip:port to list control WriteToResults("1"); // increase the open port count tcpSock.Close(); //Makes sure the socket is closed } else { WriteToResults("0"); // increase the closed port count } } catch { WriteToResults("0"); // on error assume that it was a connection error, thus increment port closed count } finally { progressBarInc(""); // increase the value of the progress bar by 1 } } while (nCurrPort < nEndPort); nThreadCount--; if (nThreadCount == 1){ // check if this is the last thread running cCurrIP = GetNextIP(cCurrIP); // gets next ip to work on WriteToResults("2"); // + IP scanned count System.Threading.Thread.Sleep(500); if (cCurrIP != GetNextIP(cEndIP)) { // starts scanning next ip progressBarInc("reset"); // resets the progressbar for the next IP SetTextCallback d = new SetTextCallback(ScanIP); this.Invoke(d, new object[] { cCurrIP }); } else // otherwise the scan is complete.. { progressBarInc(""); // & reset btnScan to 'start scan' bScanning = false; MessageBox.Show("Scan Complete!" ); }; } }
protected virtual bool PingHost(IPEndPoint target, Guid remote_session_id) { Logger.Debug("Ping requested. Try to ping: {0}({1})", target, remote_session_id); bool result = false; try { var client = new System.Net.Sockets.TcpClient(); client.Connect(target); client.ReceiveTimeout = 3000; client.SendTimeout = 3000; var stream = client.GetStream(); var conn = new Atom(Atom.PCP_CONNECT, 1); AtomWriter.Write(stream, conn); var helo = new AtomCollection(); helo.SetHeloSessionID(PeerCast.SessionID); AtomWriter.Write(stream, new Atom(Atom.PCP_HELO, helo)); var res = AtomReader.Read(stream); if (res.Name==Atom.PCP_OLEH) { var session_id = res.Children.GetHeloSessionID(); if (session_id.HasValue && session_id.Value==remote_session_id) { Logger.Debug("Ping succeeded"); result = true; } else { Logger.Debug("Ping failed. Remote SessionID mismatched"); } } AtomWriter.Write(stream, new Atom(Atom.PCP_QUIT, Atom.PCP_ERROR_QUIT)); stream.Close(); client.Close(); } catch (InvalidDataException e) { Logger.Debug("Ping failed"); Logger.Debug(e); } catch (System.Net.Sockets.SocketException e) { Logger.Debug("Ping failed"); Logger.Debug(e); } catch (EndOfStreamException e) { Logger.Debug("Ping failed"); Logger.Debug(e); } catch (System.IO.IOException io_error) { Logger.Debug("Ping failed"); Logger.Debug(io_error); if (!(io_error.InnerException is System.Net.Sockets.SocketException)) { throw; } } return result; }
public static DateTime DataStandardTime() { //���ع��ʱ�ʱ�� //ֻʹ�õ�ʱ���������IP��ַ��δʹ������ string[,] ʱ������� = new string[14, 2]; int[] ����˳�� = new int[] { 3, 2, 4, 8, 9, 6, 11, 5, 10, 0, 1, 7, 12 }; ʱ�������[0, 0] = "time-a.nist.gov"; ʱ�������[0, 1] = "129.6.15.28"; ʱ�������[1, 0] = "time-b.nist.gov"; ʱ�������[1, 1] = "129.6.15.29"; ʱ�������[2, 0] = "time-a.timefreq.bldrdoc.gov"; ʱ�������[2, 1] = "132.163.4.101"; ʱ�������[3, 0] = "time-b.timefreq.bldrdoc.gov"; ʱ�������[3, 1] = "132.163.4.102"; ʱ�������[4, 0] = "time-c.timefreq.bldrdoc.gov"; ʱ�������[4, 1] = "132.163.4.103"; ʱ�������[5, 0] = "utcnist.colorado.edu"; ʱ�������[5, 1] = "128.138.140.44"; ʱ�������[6, 0] = "time.nist.gov"; ʱ�������[6, 1] = "192.43.244.18"; ʱ�������[7, 0] = "time-nw.nist.gov"; ʱ�������[7, 1] = "131.107.1.10"; ʱ�������[8, 0] = "nist1.symmetricom.com"; ʱ�������[8, 1] = "69.25.96.13"; ʱ�������[9, 0] = "nist1-dc.glassey.com"; ʱ�������[9, 1] = "216.200.93.8"; ʱ�������[10, 0] = "nist1-ny.glassey.com"; ʱ�������[10, 1] = "208.184.49.9"; ʱ�������[11, 0] = "nist1-sj.glassey.com"; ʱ�������[11, 1] = "207.126.98.204"; ʱ�������[12, 0] = "nist1.aol-ca.truetime.com"; ʱ�������[12, 1] = "207.200.81.113"; ʱ�������[13, 0] = "nist1.aol-va.truetime.com"; ʱ�������[13, 1] = "64.236.96.53"; var portNum = 13; string hostName; byte[] bytes = new byte[1024]; int bytesRead = 0; using (System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient()) { for (int i = 0; i < 13; i++) { hostName = ʱ�������[����˳��[i], 1]; try { client.Connect(hostName, portNum); System.Net.Sockets.NetworkStream ns = client.GetStream(); bytesRead = ns.Read(bytes, 0, bytes.Length); client.Close(); break; } catch (System.Exception ex) { Console.WriteLine(ex); } } } System.DateTime dt = new DateTime(); string returnString = System.Text.Encoding.ASCII.GetString(bytes, 0, bytesRead); string[] s = returnString.Split(new char[] { ' ' }); dt = System.DateTime.Parse(String.Format("{0} {1}", s[1], s[2]));//�õ���ʱ�� dt = dt.AddHours(8);//�õ�����ʱ��*/ return dt; }
/// <summary> /// This function is used to check whether network connection is exists or not. /// </summary> /// <returns></returns> public bool ConnectionExists() { bool isExists = false; try { System.Net.Sockets.TcpClient clnt = new System.Net.Sockets.TcpClient("www.google.com", 80); clnt.Close(); isExists = true; } catch (System.Exception ex) { isExists = false; throw ex; } return isExists; }
// GET api/start/5 public string Get(int id) { //サーバーのIPアドレス(または、ホスト名)とポート番号 string ipOrHost = ""; if (id == 1) { ipOrHost = "192.168.10.80"; } else if (id == 2) { ipOrHost = "192.168.10.81"; } else if (id == 3) { ipOrHost = "192.168.10.69"; } else { return "You can use [api/start/1-3]"; } string sendMsg = "*is;777\r\n"; int port = 51013; System.Net.Sockets.TcpClient tcp = new System.Net.Sockets.TcpClient(ipOrHost, port); System.Net.Sockets.NetworkStream ns = tcp.GetStream(); ns.ReadTimeout = 10000; ns.WriteTimeout = 10000; System.Text.Encoding enc = System.Text.Encoding.UTF8; byte[] sendBytes = enc.GetBytes(sendMsg); ns.Write(sendBytes, 0, sendBytes.Length); System.IO.MemoryStream ms = new System.IO.MemoryStream(); byte[] resBytes = new byte[256]; int resSize = 0; do { resSize = ns.Read(resBytes, 0, resBytes.Length); if (resSize == 0) { break; } ms.Write(resBytes, 0, resSize); } while (ns.DataAvailable || resBytes[resSize - 1] != '\n'); string resMsg1 = enc.GetString(ms.GetBuffer(), 0, (int)ms.Length); ms.Close(); System.Threading.Thread.Sleep(5000); sendMsg = "*is;666\r\n"; sendBytes = enc.GetBytes(sendMsg); ns.Write(sendBytes, 0, sendBytes.Length); ms = new System.IO.MemoryStream(); resBytes = new byte[256]; resSize = 0; do { resSize = ns.Read(resBytes, 0, resBytes.Length); if (resSize == 0) { break; } ms.Write(resBytes, 0, resSize); } while (ns.DataAvailable || resBytes[resSize - 1] != '\n'); string resMsg2 = enc.GetString(ms.GetBuffer(), 0, (int)ms.Length); ms.Close(); resMsg1 = resMsg1.TrimEnd('\n'); resMsg1 = resMsg1.TrimEnd('\r'); resMsg2 = resMsg2.TrimEnd('\n'); resMsg2 = resMsg2.TrimEnd('\r'); ns.Close(); tcp.Close(); return resMsg1+" , "+resMsg2; }
public DemoChat() { bool exit = false; String nickName; // system running on localhost tcpClient = new System.Net.Sockets.TcpClient(); try { tcpClient.Connect("localhost", 4296); } catch (Exception ex) { Console.WriteLine("Failed to connect: "); } Thread chatThread = new Thread(new ThreadStart(run)); chatThread.Start(); Console.Clear(); Console.WriteLine("Welcome to simple chat!"); // get user nick name for discussions nickName = getNicName(); // send query to server ChatCommand cmd = new ChatCommand("list", nickName); StreamWriter writer = new StreamWriter(tcpClient.GetStream()); //Console.WriteLine(cmd.ToJson()); writer.WriteLine(cmd.ToJson()); writer.Flush(); // program main loop while (exit == false) { Console.Clear(); Console.WriteLine("Discussions for (" + nickName + ")"); // discussionsAA if (chatRooms != null) { int i = 0; foreach (ChatRoom r in chatRooms) { Console.WriteLine(i + ") " + r.UserA + " ( " + r.StartTime + ": " + r.Name + " )"); i++; } } Console.WriteLine(); Console.Write("Enter command (help to display help): "); String line = Console.ReadLine(); var command = Parser.Parse(line, nickName, tcpClient); // chat room has different parameters if (command.GetType() == typeof(OpenCommand)) { // open chat room ChatRoom r = chatRooms.ElementAt(((OpenCommand)command).Index); ((OpenCommand)command).Room = r; exit = command.Execute(); } else { if (command.GetType() == typeof(SortCommand)) { exit = command.Execute(); switch (((SortCommand)command).Sort) { case 1: chatRooms = chatRooms.OrderByDescending(o => o.StartTime).ToList(); break; case 2: chatRooms = chatRooms.OrderBy(o => o.Name).ToList(); break; case 3: chatRooms = chatRooms.OrderBy(o => o.Messages.ElementAt(o.Messages.Count - 1).Time).ToList(); break; } } else { exit = command.Execute(); } } } tcpClient.Close(); // terminate program ExitProcess(0); }
public void Connect_Task() { if (intask) return; intask = true; // System.Threading.Thread.Sleep(5000); while (!this.IsDisposing) { try { tcp = new System.Net.Sockets.TcpClient(); tcp.Connect(new System.Net.IPAddress(ipByte), port); bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); connected = true; Console.WriteLine("NotifySerevr connected!"); new System.Threading.Thread(ClientWork).Start(); if (this.OnConnect != null) { try { this.OnConnect(this); } catch { ;} } break; } catch(Exception ex) { Console.WriteLine(ex.Message+"Notify Serevr connecting error!,retry..."); try { tcp.Close(); GC.Collect(); GC.WaitForPendingFinalizers(); for (int i = 0; i < 500; i++) System.Diagnostics.Debug.Print("collect"); } catch { ;} System.Threading.Thread.Sleep(10000); } } intask = false; }
/// <summary> /// Checks if specified host has APOP capability. /// </summary> /// <param name="host">Host to be checked.</param> /// <param name="port">Port to connect on to the host.</param> /// <returns>True is remote server has APOP, otherwise false.</returns> /// <example> /// <code> /// C# /// /// bool serverHasAPOP = Pop3Client.CheckAPOP("mail.myhost.com",8503); /// /// VB.NET /// /// Dim serverHasAPOP As Boolen = Pop3Client.CheckAPOP("mail.myhost.com",8503) /// /// JScript.NET /// /// var serverHasAPOP:bool Pop3Client.CheckAPOP("mail.myhost.com",8503); /// </code> /// </example> public static bool CheckAPOP(string host, int port) { System.Net.Sockets.TcpClient _tcp = new System.Net.Sockets.TcpClient(host, port); byte[] buf = new byte[256]; _tcp.GetStream().Read(buf, 0, 256); //string resp = System.Text.Encoding.ASCII.GetString(buf); #if !PocketPC string resp = System.Text.Encoding.GetEncoding("iso-8859-1").GetString(buf, 0, buf.Length); #else string resp = PPCEncode.GetString(buf, 0, buf.Length); #endif _tcp.Close(); if (resp.IndexOf("<") != -1 && resp.IndexOf(">") != -1 && (resp.IndexOf("@") < resp.IndexOf(">")) && (resp.IndexOf("@") > resp.IndexOf("<"))) return true; else return false; }
bool InternetConnectionExists() { try { System.Net.Sockets.TcpClient clnt = new System.Net.Sockets.TcpClient("www.google.com", 80); clnt.Close(); return true; } catch (System.Exception) { return false; } }
/// <summary> /// Busco un servidor en la red loca. /// </summary> /// <returns></returns> private void BuscarServidor(Lfx.Types.OperationProgress progreso) { foreach (NetworkInterface Intrfc in NetworkInterface.GetAllNetworkInterfaces()) { progreso.ChangeStatus("Buscando en " + Intrfc.Name); if (Intrfc.OperationalStatus == OperationalStatus.Up) { foreach (UnicastIPAddressInformation MiDireccion in Intrfc.GetIPProperties().UnicastAddresses) { byte FirstByte = MiDireccion.Address.GetAddressBytes()[0]; if (FirstByte == 192 || FirstByte == 10) { byte SecondByte = MiDireccion.Address.GetAddressBytes()[1]; byte ThirdByte = MiDireccion.Address.GetAddressBytes()[2]; for (byte i = 1; i < 255; i++) { try { IPAddress DireccionServidor = new IPAddress(new byte[] { FirstByte, SecondByte, ThirdByte, i }); if (DireccionServidor.Equals(MiDireccion.Address) == false) { Ping Pp = new Ping(); PingReply Pr = Pp.Send(DireccionServidor, 100); if (Pr.Status == IPStatus.Success) { try { System.Net.Sockets.TcpClient Cliente = new System.Net.Sockets.TcpClient(); Cliente.Connect(DireccionServidor, 3306); Cliente.Close(); this.ServidorDetectado = DireccionServidor.ToString(); System.Net.IPHostEntry DireccionServidorDetectado = System.Net.Dns.GetHostEntry(ServidorDetectado); this.ServidorDetectado = DireccionServidorDetectado.HostName; progreso.End(); } catch { // Nada } } } } catch { // Ignoro esa IP } } } } } } this.ServidorDetectado = null; progreso.End(); }
protected virtual void CloseConnection() { try { reader.Close(); reader = null; writer.Close(); writer = null; channel.Close(); channel = null; } catch (System.Exception e) { Console.Error.WriteLine(e); Console.Error.WriteLine(e.StackTrace); } finally { if (reader != null) { try { reader.Close(); } catch (IOException ioe) { Console.Error.WriteLine(ioe); } } if (writer != null) { writer.Close(); } if (channel != null) { try { channel.Close(); } catch (IOException ioe) { Console.Error.WriteLine(ioe); } } } }