public void Disconnect2() { if (TcpClient != null) { if (TcpClient?.Connected == true) { Message = "disconected"; Status = "Disconnected"; string s = "Client: " + Name + " UnicNimber: " + UnicNimber + " Status: " + Status + " ConnectionTime: " + ConnectionTime.ToString("h:mm:ss tt") + " Message: " + Message + "<<E!N!D>> "; sw.WriteLine(s); TcpClient.Close(); Colections.messages.Add("Сlient: " + Name + ConnectionTime.ToString() + System.Environment.NewLine + " disconnected"); mylistBox.SelectedItem = mylistBox.Items[Colections.messages.Count - 1]; mylistBox.ScrollIntoView(mylistBox.SelectedItem); TcpClient = null; sw = null; sr = null; Colections.messages = new ObservableCollection <string>(); } } else { MessageBox.Show("You already dissconect"); } }
/// <summary> /// Gets the client info as an array of strings. /// </summary> /// <param name="format">The format to use for each line. {0} is the name /// of the property and {1} is the value.</param> public string[] GetLines(string format = @"{0}: {1}") { string ctVal = ConnectionTime?.ToString("hh:mm:ss tt") ?? "N/A"; string litVal = LoggedInTime?.ToString("hh:mm:ss tt") ?? "N/A"; return(new[] { String.Format(format, nameof(Name), Name), String.Format(format, nameof(Status), Status), String.Format(format, nameof(ConnectionTime), ctVal), String.Format(format, nameof(LoggedInTime), litVal), String.Format(format, nameof(IP), IP) }); }
private DatastoreItemList GetStoreItemList(bool cacheStoreItemList = true) { try { if (m_storeItemList == null || ConnectionTime.Elapsed.Minutes > MaxConnectionMinutes) { ConnectionTime.Reset(); ProductStudio.Directory psDir = new ProductStudio.Directory(); psDir.Connect(); ProductStudio.Product psProduct = psDir.GetProductByName(StoreID.Name); DatastoreItemList storeItemList = new DatastoreItemList(); storeItemList.Datastore = psProduct.Connect(); // Simulate outdated Product Studio error //if (storeItemList.Datastore == null || storeItemList.Datastore != null) //{ // throw new Exception("[Product Studio] 80044005. Access to this product requires updated client components."); //} ConnectionTime.Start(); FieldDefs = storeItemList.Datastore.FieldDefinitions; if (cacheStoreItemList) { m_storeItemList = storeItemList; } else { return(storeItemList); } } return(m_storeItemList); } catch (Exception exception) { StringBuilder sb = new StringBuilder(); sb.AppendLine("Unable to connect to " + StoreID.Name); sb.AppendLine(); sb.AppendLine(exception.Message); sb.AppendLine(); Planner.Instance.WriteToEventLog(sb.ToString()); throw new Exception(sb.ToString()); } }
public override int GetHashCode() { unchecked { return(base.GetHashCode() + (Callsign.ToUpper().GetHashCode() * 3) + (VID.ToUpper().GetHashCode() * 3) + (Name.ToUpper().GetHashCode() * 3) + (ClientType.GetHashCode() * 3) + (GetItemHashCode(Location) * 3) + (Server.ToUpper().GetHashCode() * 3) + (Protocol.ToUpper().GetHashCode() * 3) + (ConnectionTime.GetHashCode() * 3) + (SoftwareName.ToUpper().GetHashCode() * 3) + (SoftwareVersion.ToUpper().GetHashCode() * 3) + (AdministrativeVersion.GetHashCode() * 3) + (ClientRating.GetHashCode() * 3) * 17); } }
//TcpListener usertcpListener; // //NetworkStream stream; // public Client(string ip, string port)//connect // { // //создание экземпляра класса TcpListener //данные о хосте и порте читаются //из текстовых // usertcpListener = new TcpListener(IPAddress.Parse(ip), Convert.ToInt32(port)); // // messages = new ObservableCollection<string>(); // } // public void ClientListening() // { // // messageList = messageLista; // try // { // //начало прослушивания клиентов // usertcpListener.Start(); // //создание отдельного потока для чтения сообщения // Thread thread = new Thread(new ThreadStart(ReadMessageThreadClient)); //(delegate () { ReadMessageThread(); });//Thread thread = new Thread(() => download(filename)); thread.Start(); // thread.IsBackground = true; // //запуск потока // thread.Start(); // } // catch (SocketException sockEx) // { // MessageBox.Show("Ошибка сокета: " + sockEx.Message); // } // catch (Exception Ex) // { // MessageBox.Show("Ошибка : " + Ex.Message); // } // } // private void ReadMessageThreadClient() // { // while (true) // { // //сервер сообщает клиенту о готовности //к соединению // TcpClient cl = usertcpListener.AcceptTcpClient(); // //чтение данных из сети в формате Unicode // // while (true) // // { // StreamReader sr = new StreamReader(cl.GetStream(), Encoding.Unicode); // string s = sr.ReadLine(); // //if (user.Status.IndexOf("Disconnect") > -1) // //{ // // // s = "User Disconnect"; // // s = user.Message; // //} // if (s != null) // { // Application.Current.Dispatcher.Invoke(() => messages.Add(s)); // } // cl.Close(); // } // } //22 public void ConnectCommand(string ip, string port) //connection 1 { if (TcpClient == null || TcpClient?.Connected == false) //КОГДА НЕ ПОДКЛЮЧЕНЫ К СКРВЕРУ { Task.Factory.StartNew(() => { try { TcpClient = new TcpClient(); TcpClient.Connect(IPAddress.Parse(ip), Convert.ToInt32(port)); sr = new StreamReader(TcpClient.GetStream(), Encoding.Unicode); sw = new StreamWriter(TcpClient.GetStream(), Encoding.Unicode); sw.AutoFlush = true; string s = "Client: " + Name + " UnicNimber: " + UnicNimber + " Status: " + Status + " ConnectionTime: " + ConnectionTime.ToString("h:mm:ss tt") + " Message: " + "Connecction" + "<<E!N!D>> "; sw.WriteLine(s); //App.Current.Dispatcher.Invoke((Action)delegate // <--- HERE //{ // Colections.messages.Add("Client:"+ Name+" connected"); //}); } catch (Exception) { MessageBox.Show("Unable to connect to server"); // MessageBox.Show(EX.Message); } }); } else { MessageBox.Show("You connect already"); } }
public void Connection()//message { try { //создание экземпляра класса IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(Ip), Convert.ToInt32(Port)); client = new TcpClient(); IsBusy = 2;//busy //установка соединения с использованием //данных IP и номера порта client.Connect(endPoint); //NetworkStream nstream1 = client.GetStream(); //byte[] barray = Encoding.Unicode.GetBytes(message); //nstream1.Write(barray, 0, barray.Length); //получение сетевого потока nstream = client.GetStream(); //преобразование строки сообщения в массив байт byte[] barray = Encoding.Unicode.GetBytes("Client: " + Name + " UnicNimber: " + UnicNimber + " Status: " + Status + " ConnectionTime: " + ConnectionTime.ToString("h:mm:ss tt") + " Message: " + Message + "<<E!N!D>> " + "\r\n");// "<<E!N!D>> " );//+ message); //запись в сетевой поток всего массива nstream.Write(barray, 0, barray.Length); //закрытие клиента // client.Close(); } catch (SocketException sockEx) { MessageBox.Show("Ошибка сокета:" + sockEx.Message); } catch (Exception Ex) { MessageBox.Show("Ошибка :" + Ex.Message); } }
//222 public void send(string Message) //send { if (TcpClient?.Connected == true && !string.IsNullOrWhiteSpace(Message)) //когда подключен и когда сообщение не пуссто { Task.Factory.StartNew(() => { try { string s = "Client: " + Name + " UnicNimber: " + UnicNimber + " Status: " + Status + " ConnectionTime: " + ConnectionTime.ToString("h:mm:ss tt") + " Message: " + Message + "<<E!N!D>> "; sw.WriteLine(s); //clian text field } catch (Exception) { App.Current.Dispatcher.Invoke((Action) delegate // <--- HERE { Colections.messages.Add(DateTime.Now.ToLongTimeString() + Environment.NewLine + "Message dont send"); mylistBox.SelectedItem = mylistBox.Items[Colections.messages.Count - 1]; mylistBox.ScrollIntoView(mylistBox.SelectedItem); }); } }); }// +users[i].ConnectionTime.ToString() + System.Environment.NewLine else { if (TcpClient == null) { MessageBox.Show("Server crashed or disconected!" + "Try to connect again"); } else { if (string.IsNullOrWhiteSpace(Message)) { MessageBox.Show("You cant send empty message"); } else { MessageBox.Show("server crashed or disconected!" + String.Empty + " Try to connect again"); } } } }