private void PobierzKategorie() { try { ASCIIEncoding asen = new ASCIIEncoding(); TcpClient tcpclnt = new TcpClient(); tcpclnt.Connect(IP, 8001); Stream stm = tcpclnt.GetStream(); string str; byte[] ba; byte[] bb; string tekst; int k; do { str = "SK"; //Przesłanie komunikatu o checi pobrania listy zamówień //str = Szyfrowanie.Encrypt(str, encryptyingCode); ba = asen.GetBytes(str); stm.Write(ba, 0, ba.Length); bb = new byte[256]; //k = stm.Read(bb, 0, 256);//dubel k = stm.Read(bb, 0, 256); tekst = ""; for (int i = 0; i < k; i++) { tekst += (Convert.ToChar(bb[i])); } // tekst = Szyfrowanie.Decrypt(tekst, encryptyingCode); str = ""; } while (tekst != "OK"); StreamWriter sw = new StreamWriter(source3); k = stm.Read(bb, 0, 256); tekst = ""; for (int i = 0; i < k; i++) { tekst += (Convert.ToChar(bb[i])); } int ilosc = Convert.ToInt32(tekst); string test = ""; UTF8Encoding coderUTF = new UTF8Encoding(); sw.WriteLine(ilosc); for (int i = 0; i < ilosc; i++) { k = stm.Read(bb, 0, 3); tekst = ""; for (int j = 0; j < k; j++) { tekst += (Convert.ToChar(bb[j])); } bb = new byte[Convert.ToInt32(tekst)]; k = stm.Read(bb, 0, Convert.ToInt32(tekst)); tekst = ""; tekst = System.Text.Encoding.UTF8.GetString(bb); //for (int j = 0; j < k; j++) tekst += (Convert.ToChar(bb[j])); tekst += ""; tekst += ""; test = tekst; sw.WriteLine(test); } sw.Close(); } catch { } }
public Client(string IP, int port) { clientSocket = new TcpClient(); clientSocket.Connect(IPAddress.Parse(IP), port); stream = clientSocket.GetStream(); }
public Communication() { clientSocket.Connect("127.0.0.1", 5432); Console.WriteLine("Client Socket Program - Server Connected ..."); }
private void Button1_Click(object sender, EventArgs e) { TcpClient client = new TcpClient(); try { //client.Connect("127.0.0.1", 49677); client.Connect("172.16.3.199", 40000); nStream = client.GetStream(); //send data sendData = new BinaryWriter(nStream); readData = new BinaryReader(nStream); if (!String.IsNullOrEmpty(textBox1.Text)) { PlayerName = textBox1.Text; if (radioButton2.Checked) { flag = true; } try { sendData.Write(PlayerName + " " + flag.ToString().ToLower()); panel1.Visible = true; panel1.Paint += new PaintEventHandler(Panel1_Paint); panel1.Refresh(); PName.Text = PlayerName; if (flag) { DisabledMood(); //read playing character str = readData.ReadString(); PlayingChar = str; // MessageBox.Show("Play char "+PlayingChar); if (str == "X") { OtherPlayingChar = "O"; } else { OtherPlayingChar = "X"; } //MessageBox.Show("other char " + OtherPlayingChar); ChangeTurn(); } else { RecieveResponse(); } } catch { LostConnection(); } } } catch { MessageBox.Show("No Connection! Please, Try Again Later"); } }
static void Main(string[] args) { var loggerFactory = LoggerFactory.Create(builder => builder.AddConsole()); _logger = loggerFactory.CreateLogger <Program>(); if (args.Length == 0) { _logger.LogWarning("Arguments not specified"); ShowHelp(); return; } var configBuilder = new ConfigurationBuilder(); configBuilder.AddCommandLine(args); var config = configBuilder.Build(); if (!IPAddress.TryParse(config.GetValue <string>("ip"), out IPAddress ipAddress)) { throw new ArgumentException($"Error: IP address is not specified. Use --ip \"{{ip_address}}\""); } _logger.LogInformation($"IP: {ipAddress.ToString()}"); if (!int.TryParse(config.GetValue <string>("port"), out int port)) { throw new ArgumentException($"Error: Port is not specified. Use --port {{port_number}}"); } _logger.LogInformation($"Port: {port}"); var data = config.GetValue <string>("data"); if (data == null) { throw new ArgumentException($"Error: Data is not specified. Use --data \"{{data}}\""); } _logger.LogInformation($"Data: {data}"); var ssl = config.GetValue <bool>("ssl", false); _logger.LogInformation($"Use ssl: {ssl}"); var sslHost = config.GetValue <string>("ssl-host"); if (ssl && string.IsNullOrWhiteSpace(sslHost)) { throw new ArgumentException("Error: SSL enabled, but host is not specified. Use: --ssl-host {{\"ssl_host\"}}"); } _logger.LogInformation($"Use ssl: {ssl}"); using (TcpClient client = new TcpClient()) { _logger.LogInformation("Client created"); client.Connect(ipAddress, port); _logger.LogInformation("Connected to the remote server"); using (var stream = client.GetStream()) { _logger.LogInformation("Stream is ready"); if (ssl) { using (var sslStream = new SslStream(stream, true, CertificateValidationCallback)) { sslStream.AuthenticateAsClient("google.com.ua"); Communicate(sslStream, data); } } else { Communicate(stream, data); } } client.Close(); } }
/* * Abstract bottom two methods to new class to allow for one single * application to either be a server or a client */ private void ConnectButton_Click(object sender, EventArgs e) { try { // IP and port the TCP server is running on string ip = "192.168.1.9"; const int port = 9999; // Initialize a new TcpClient TcpClient client = new TcpClient(); // Update the user OutputDialog.Text += "Attempting connection with " + ip + " and port " + port + "\n" + "---------------------------------------------------------------\n"; // Connect the client to the given IP and port client.Connect("192.168.1.9", 9999); // Update the user OutputDialog.Text += "Connection successully established...\n" + "---------------------------------------------------------------\n"; // Get the NetworkStream from the connected client NetworkStream stream = client.GetStream(); // Encoder to encode the message ASCIIEncoding asc = new ASCIIEncoding(); byte[] flag = new byte[20]; if (TextRadio.Checked) { flag = asc.GetBytes("Text"); // Update the user OutputDialog.Text += "Transmitting Flag...\n" + "---------------------------------------------------------------\n"; stream.Write(flag, 0, flag.Length); // Populate a byte array with the encoded message byte[] data = asc.GetBytes(MessageDialog.Text); // Update the user OutputDialog.Text += "Transmitting Data...\n" + "---------------------------------------------------------------\n"; // Write the message to the stream and the TCP server stream.Write(data, 0, data.Length); } else if (ImageRadio.Checked) { flag = asc.GetBytes("Image"); // Update the user OutputDialog.Text += "Transmitting Flag...\n" + "---------------------------------------------------------------\n"; stream.Write(flag, 0, flag.Length); stream.Flush(); byte[] imageBytes = File.ReadAllBytes(fileName); //Debug.WriteLine("Client is sending > {0} bytes", imageBytes.Length); byte[] len = BitConverter.GetBytes(imageBytes.Length); //Debug.WriteLine(len.Length); stream.Write(len, 0, len.Length); stream.Flush(); stream.Write(imageBytes, 0, imageBytes.Length); } else if (singleFileRadio.Checked) { // Get the bytes for the flag to alert the server flag = asc.GetBytes("Single"); // Update the user OutputDialog.Text += "Transmitting Flag...\n" + "---------------------------------------------------------------\n"; // Write the flag and flush the stream to make room for later data stream.Write(flag, 0, flag.Length); stream.Flush(); // Get bytes of the safe file name and the size byte[] extBytes = asc.GetBytes(safeFileName + " " + len); // Update the user OutputDialog.Text += "Transmitting extension of file...\n" + "---------------------------------------------------------------\n"; // Write the extension and size to the stream stream.Write(extBytes, 0, extBytes.Length); stream.Flush(); // Stop the client here and wait for the server to respond with the OK to send the // rest of the data byte[] wait = new byte[2]; int length = stream.Read(wait, 0, wait.Length); // Convert the bytes string response = ""; for (int i = 0; i < length; i++) { response += Convert.ToChar(wait[i]); } // Check if the server is ready if (response == "OK") { // Read the bytes of the file itself byte[] fileDataRaw = File.ReadAllBytes(fileName); // Update the user OutputDialog.Text += "Transmitting raw file data...\n" + "---------------------------------------------------------------\n"; // Write the extension to the stream stream.Write(fileDataRaw, 0, fileDataRaw.Length); stream.Flush(); // Update the user OutputDialog.Text += "File successfully sent to the server!\n" + "---------------------------------------------------------------\n"; } } else if (folderRadio.Checked) { // Get the bytes for the flag to alert the server flag = asc.GetBytes("Zip"); // Update the user OutputDialog.Text += "Transmitting Flag...\n" + "---------------------------------------------------------------\n"; // Write the flag and flush the stream to make room for later data stream.Write(flag, 0, flag.Length); stream.Flush(); if (File.Exists(@"C:\TCP_Messages\" + fileName + ".7z")) { File.Delete(@"C:\TCP_Messages\" + fileName + ".7z"); } ZipFile.CreateFromDirectory(fileName, @"C:\TCP_Messages\" + fileName + ".7z"); fileName = @"C:\TCP_Messages\" + fileName + ".7z"; byte[] zipRaw = File.ReadAllBytes(@"C:\TCP_Messages\result.7z"); len = zipRaw.Length; // Get bytes of the safe file name and the size byte[] extBytes = asc.GetBytes(safeFileName + " " + len); // Update the user OutputDialog.Text += "Transmitting file information...\n" + "---------------------------------------------------------------\n"; // Write the extension and size to the stream stream.Write(extBytes, 0, extBytes.Length); stream.Flush(); // Stop the client here and wait for the server to respond with the OK to send the // rest of the data byte[] wait = new byte[2]; int length = stream.Read(wait, 0, wait.Length); // Convert the bytes string response = ""; for (int i = 0; i < length; i++) { response += Convert.ToChar(wait[i]); } // Check if the server is ready if (response == "OK") { // Read the bytes of the file itself byte[] fileDataRaw = File.ReadAllBytes(fileName); // Update the user OutputDialog.Text += "Transmitting raw file data...\n" + "---------------------------------------------------------------\n"; // Write the extension to the stream stream.Write(fileDataRaw, 0, fileDataRaw.Length); stream.Flush(); // Update the user OutputDialog.Text += "File successfully sent to the server!\n" + "---------------------------------------------------------------\n"; } } // Prepare and receive a response to the server //byte[] response = new byte[100]; //int length = stream.Read(response, 0, 100); //// Push the response to the user //for (int i = 0; i < length; i++) //{ // OutputDialog.Text += Convert.ToChar(response[i]); //} //OutputDialog.Text += "\n---------------------------------------------------------------\n"; //// Clean up //client.Dispose(); //client.Close(); } catch (Exception ex) { Debug.WriteLine(ex.StackTrace); } }
public static void Main(string[] args) { TcpClient tcpClient = new TcpClient(); try { tcpClient.Connect(IPAddress.Parse("192.168.43.159"), 7778); }catch (Exception e) { Console.WriteLine(e.Message); } string message = null; string pass = ""; string tipo = ""; string curso = ""; Console.WriteLine("======== Chat Room ========"); Console.WriteLine("[1] - Registar novo utilizador"); Console.WriteLine("[2] - Fazer Log-in"); string escolha = Console.ReadLine(); Console.Clear(); if (escolha == "1") { Console.WriteLine("======== Registar Novo Utilizador ========"); tcpClient.Client.Send(Encoding.ASCII.GetBytes(escolha)); //Registo Console.Write("Insira o seu Username: "******"Insira o seu Numero: "); tcpClient.Client.Send(Encoding.ASCII.GetBytes(Console.ReadLine())); while (pass.Length == 0) { Console.Write("Insira a sua Password: "******"Password invalida..."); } } while (curso != "1" && curso != "2" && curso != "3" && curso != "4" && curso != "5") { Console.WriteLine("Indique o seu Curso:"); Console.WriteLine("[1] Design Grafico"); Console.WriteLine("[2] Engenharia de Sistemas Informáticos"); Console.WriteLine("[3] Engenharia e Gestão Industrial"); Console.WriteLine("[4] Finanças"); Console.WriteLine("[5] Fiscalidade"); curso = Console.ReadLine(); if (curso == "1" || curso == "2" || curso == "3" || curso == "4" || curso == "5") { tcpClient.Client.Send(Encoding.ASCII.GetBytes(curso)); } else { Console.WriteLine("Escolha inválida..."); } } while (tipo != "1" && tipo != "2") { Console.Write("Indique a sua profissão: \n1 - Aluno \n2 - Professor\n"); tipo = Console.ReadLine(); if (tipo == "1" || tipo == "2") { tcpClient.Client.Send(Encoding.ASCII.GetBytes(tipo)); } else { Console.WriteLine("Escolha inválida..."); } } } else if (escolha == "2") { Console.WriteLine("======== Fazer Log-in ========"); tcpClient.Client.Send(Encoding.ASCII.GetBytes(escolha)); //Log in Console.Write("Insira o seu Numero: "); tcpClient.Client.Send(Encoding.ASCII.GetBytes(Console.ReadLine())); Console.Write("Insira a Password: "******">> "); message = Console.ReadLine(); byte[] byteBuffer = Encoding.ASCII.GetBytes(message); stream.Write(byteBuffer, 0, byteBuffer.Length); if (message == "/sair") { recebeMsg.Interrupt(); Environment.Exit(0); } } #region Codigo antigo /* * Console.Write("Insira o seu Username: "******"Insira a sua Password: "******"Indique a sua profissão: \n0 - Aluno \n1 - Professor\n"); * tcpClient.Client.Send(Encoding.ASCII.GetBytes(Console.ReadLine())); * * Console.Clear(); * * Console.WriteLine("Conectado ao chat."); * string message = "lel"; * while (message != "sair") * { * message = Console.ReadLine(); * tcpClient.Client.Send(Encoding.ASCII.GetBytes(message)); * } * tcpClient.Close(); * } * private static void Choice() * { * Console.WriteLine("0 - Entrar \n" + * "1 - Registar nova conta: +"); * Console.ReadLine(); */ #endregion }
static void Main(string[] args) { List <byte> bytelist = new List <byte>(); IPAddress ip = IPAddress.Parse("127.0.0.1"); int port = 5000; TcpClient client = new TcpClient(); client.Connect(ip, port); Console.WriteLine("client connected!!"); NetworkStream ns = client.GetStream(); Thread thread = new Thread(o => ReceiveData((TcpClient)o)); // create tread that run fuction ReceiveData thread.Start(client); byte[] receivedBytes = new byte[1024]; Console.WriteLine("enter id : "); int id = 0; string s = ""; //register by id if (!string.IsNullOrEmpty((s = Console.ReadLine()))) { id = int.Parse(s); List <byte> sendByte = new List <byte>(); sendByte.Add(0x05); sendByte.Add(0x05); sendByte.Add(0x0B); // All byte to send sendByte.Add((byte)id); // ID sendByte.Add(0x00); sendByte.Add(0x00); sendByte.Add(0x00); sendByte.Add(0x00); sendByte.Add(0x00); sendByte.Add(0x00); sendByte.Add(0x01); ns.Write(sendByte.ToArray(), 0, sendByte.Count); Console.WriteLine(BitConverter.ToString(sendByte.ToArray(), 0, sendByte.Count)); } bool running = true; //Send data to server after register while (running) { if (!string.IsNullOrEmpty((s = Console.ReadLine()))) { if (s == "exit") { running = false; } else { if (s.Length < 4) { while (s.Length < 4) { s += "0"; } } char[] arr = s.ToArray(); List <byte> sendByte = new List <byte>(); sendByte.Add(0x05); sendByte.Add(0x05); int len = arr.Length + 7; sendByte.Add((byte)len); sendByte.Add((byte)id); sendByte.Add(0x01); // cmd 1 = normal message foreach (char c in arr) { sendByte.Add((byte)c); } sendByte.Add(0x00); sendByte.Add(0x01); ns.Write(sendByte.ToArray(), 0, sendByte.Count); Console.WriteLine(BitConverter.ToString(sendByte.ToArray(), 0, sendByte.Count)); } } } }
public Client(String host, int port) { client = new TcpClient(); client.Connect(host, port); }
public void RUN() { CheckForIllegalCrossThreadCalls = false; // cross thread false this.m_client = new TcpClient(); try { //client = new TcpClient(); IPAddress locAddr = IPAddress.Parse(textBoxIP.Text); int port = Int32.Parse(textBoxPort.Text); m_client.Connect(locAddr, port); } catch (SocketException se) { MessageBox.Show("서버 연결중에 오류 발생!"); return; } buttonConnect.Text = "Disconnect";//버튼 변경을 여기서 해주면 될까? buttonConnect.ForeColor = Color.Red; textBoxID.ReadOnly = false; textBoxPassword.ReadOnly = false; textBoxIP.ReadOnly = true; textBoxPort.ReadOnly = true; //textBox_PortNumber.ReadOnly = true; buttonLogIn.Enabled = true; buttonJoin.Enabled = true; // MessageBox.Show("여기는 오니?"); this.m_bConnect = true; this.m_networkstream = this.m_client.GetStream(); int nRead = 0; while (this.m_bConnect) { nRead = 0; nRead = this.m_networkstream.Read(readBuffer, 0, 1024 * 1024 * 4);//여기서 멈춰있나 Packet packet = (Packet)Packet.Desserialize(this.readBuffer);//이거 까지 올려야되나 try { switch ((int)packet.Type) { case (int)PacketType.조회: { this.m_searchClass = (Search)Packet.Desserialize(this.readBuffer); this.Invoke(new MethodInvoker(delegate() { ListBoxSearch.Items.Clear(); foreach (string ohho in m_searchClass.m_list) { ListBoxSearch.Items.Add(ohho); } })); //MessageBox.Show("받았쪄"); break; } case (int)PacketType.로그인: //정상 로그인 { this.m_loginClass = (Login)Packet.Desserialize(this.readBuffer); this.Invoke(new MethodInvoker(delegate() { if (m_loginClass.Data == 0) { //MessageBox.Show("가입 성공"); //errorClass.str = "이미 사용중인 ID입니다."; if (buttonLogIn.Text == "로그인") { buttonLogIn.ForeColor = Color.Red; buttonLogIn.Text = "로그아웃"; } else { buttonLogIn.ForeColor = Color.Black; buttonLogIn.Text = "로그인"; } } else { MessageBox.Show(this.m_loginClass.str); } })); break; } case (int)PacketType.회원가입: { this.m_joinClass = (Join)Packet.Desserialize(this.readBuffer); this.Invoke(new MethodInvoker(delegate() { if (m_joinClass.Data == 1) { MessageBox.Show(this.m_joinClass.str); } //MessageBox.Show("가입 성공"); //errorClass.str = "이미 사용중인 ID입니다."; })); break; } } } catch { this.m_bConnect = false; this.m_networkstream = null; MessageBox.Show("클라이언트 종료"); break;//오 이러니까 되는거 같다. 개꿀 또 안되네 뭐지 } } }
/// <summary> /// IMPORTANTE: a cada RECEÇÃO deve seguir-se, obrigatóriamente, um ENVIO de dados /// IMPORTANT: each network .Read() must be fallowed by a network .Write() /// </summary> static void Main(string[] args) { byte[] key, iv; byte[] msg; IPEndPoint serverEndPoint; TcpClient client = null; NetworkStream netStream = null; ProtocolSI protocol = null; try { Console.WriteLine("CLIENT"); #region Defenitions // Client/Server Protocol to SI protocol = new ProtocolSI(); // Defenitions for TcpClient: IP:port (127.0.0.1:9999) serverEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9999); #endregion Console.WriteLine(SEPARATOR); #region TCP Connection // Connects to Server ... Console.Write("Connecting to server... "); client = new TcpClient(); client.Connect(serverEndPoint); netStream = client.GetStream(); Console.WriteLine("ok."); #endregion Console.WriteLine(SEPARATOR); #region Exchange Data (Unsecure channel) using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider()) { key = aes.Key; iv = aes.IV; } Console.WriteLine("Sending KEY"); msg = protocol.Make(ProtocolSICmdType.SECRET_KEY, key); netStream.Write(msg, 0, msg.Length); Console.WriteLine("WAITING ACK"); netStream.Read(protocol.Buffer, 0, protocol.Buffer.Length); Console.WriteLine("Sending IV"); msg = protocol.Make(ProtocolSICmdType.IV, iv); netStream.Write(msg, 0, msg.Length); Console.WriteLine("WAITING ACK"); netStream.Read(protocol.Buffer, 0, protocol.Buffer.Length); #endregion Console.Write("Indique a mensagem para enviar: "); string messageSend = Console.ReadLine(); using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider()) { aes.Key = key; aes.IV = iv; SymmetricsSI symmetrics = new SymmetricsSI(aes); var send = symmetrics.Encrypt(Encoding.UTF8.GetBytes(messageSend)); Console.WriteLine("Sending ENCRYPTED MESSAGE"); msg = protocol.Make(ProtocolSICmdType.SYM_CIPHER_DATA, send); netStream.Write(msg, 0, msg.Length); Console.WriteLine("WAITING ACK"); netStream.Read(protocol.Buffer, 0, protocol.Buffer.Length); Console.WriteLine($"Recieved from server: '{protocol.GetCmdType()}'"); } } catch (Exception ex) { Console.WriteLine(SEPARATOR); Console.WriteLine("Exception: {0}", ex.ToString()); } finally { // Close connections if (netStream != null) { netStream.Dispose(); } if (client != null) { client.Close(); } Console.WriteLine(SEPARATOR); Console.WriteLine("Connection with server was closed."); } Console.WriteLine(SEPARATOR); Console.Write("End: Press a key..."); Console.ReadKey(); }
public void connectToServer() { tcpClient.Connect(ipServer, port); stm = tcpClient.GetStream(); }
/// <summary> /// opens a new multiplayer connection to the client /// </summary> public void Open() { // sets bools to true and message to null isMultiActive = true; isOpen = true; // create a client and Open the streams client = new TcpClient(); client.Connect(ep); stream = client.GetStream(); reader = new BinaryReader(stream); writer = new BinaryWriter(stream); // task to listen for the receiving stream. ready for messages from the server receiver = new Task(() => { // do as long as the isOpen bool is true while (isOpen) { // read only if the last message received was already taken if (statues == null) { string result; Status status; try { // get a message from the server and parse it to Statues result = reader.ReadString(); statues = Statues.FromJson(result); status = statues.Stat; NotifyAboutMessage?.Invoke(this, new StatuesEventArgs(statues)); } catch (Exception) { MessageBox.Show("Connect to the server have been closed"); // an error in the connection statues = new Statues(); statues.SetStatues(Status.Close, "Error receiveing message from the server"); status = Status.Disconnect; } // switch through the different options received from the server switch (status) { case Status.Disconnect: { Close(); break; } case Status.Close: { Close(); break; } case Status.Play: { statues = null; continue; } case Status.CloseGame: { // close the connection writer.Write("exit"); Close(); break; } case Status.Finish: { // close the connection writer.Write("exit"); Close(); break; } default: { break; } } } // wait for some one to receive the message else { Thread.Sleep(1); } } }); // start the thread receiver.Start(); }
static void Main(string[] args) { TcpClient client = new TcpClient(); client.Connect("localhost", 80); BikeData bikedata = new BikeData(); stream = client.GetStream(); stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(OnRead), null); // Console.WriteLine("login\r\nJoëlle\r\nJoëlle\r\n\r\n"); //Console.WriteLine("Do you want to make account then type account do you wanna login then type login"); //string choice = Console.ReadLine(); /*if (choice.Equals("account")) { * * Console.WriteLine("choose a name"); * string name = Console.ReadLine(); * Console.WriteLine("choose a password"); * string wachtwoord = Console.ReadLine(); * * Write("Account\r\n" + name + "\r\n" + wachtwoord); * }else if (choice.Equals("login")) * { * Console.WriteLine("your name"); * string name = Console.ReadLine(); * Console.WriteLine("your password"); * string wachtwoord = Console.ReadLine(); * * Write("login\r\n" + name + "\r\n" + wachtwoord); * } * else * { * Console.WriteLine("wrong answer"); * //Application.Restart(); * //Application.Exit(); * * * }*/ Console.WriteLine("your name"); string name = Console.ReadLine(); Console.WriteLine("your password"); string wachtwoord = Console.ReadLine(); // Console.WriteLine("Select your bike: "); // bikedata.getBikes(); // Console.ReadKey(); Write("login\r\n" + name + "\r\n" + wachtwoord + "\r\n\r\n"); //Write("login\r\nJoëlle\r\nJoëlle\r\n\r\n"); writeVr("12"); while (true) { string line = Console.ReadLine(); Write($"broadcast\r\n{line}\r\n\r\n"); } }
public ClientDemo(string ipAdress, int portNum) { _client = new TcpClient(); _client.Connect(ipAdress, portNum); HandleCommunication(); }
static void Main(string[] args) { List <string> localCerts = Directory.GetFiles(Directory.GetCurrentDirectory(), "*.pfx").ToList(); if (localCerts.Count > 0) { Console.WriteLine("Which certificate to use?"); foreach (string localCert in localCerts) { Console.WriteLine("{0}.{1}", localCerts.IndexOf(localCert), localCert.Remove(0, localCert.LastIndexOf(@"\") + 1).Replace(".pfx", String.Empty)); } int index = Convert.ToInt32(Console.ReadLine()); cert = new X509Certificate2(localCerts[index]); subject = cert.Subject.Replace("CN=", String.Empty); } else { Console.WriteLine("No certificates found"); Console.ReadKey(); return; } while (true) { Console.Write("IP: "); host = Console.ReadLine(); Console.Write("PORT: "); port = Convert.ToInt32(Console.ReadLine()); client = new TcpClient(); try { client.Connect(host, port); //подключение клиента stream = client.GetStream(); // получаем поток BinaryFormatter formatter = new BinaryFormatter(); Task task = Task.Run(() => ReceiveMessage()); Dictionary <string, object> data = new Dictionary <string, object>(); data.Add("command", "authReq"); data.Add("subject", subject); formatter.Serialize(stream, data); while (true) { string command = Console.ReadLine(); data.Clear(); switch (command) { default: { Console.WriteLine("Unknown command"); break; } } } } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { Disconnect(); } } }
//Содерэит логику поиска сервера. Сервер может находиться на любом компьютере в локальной сети //И надо как-то выяснить, где именно. Поэтому мы опросим все комрьютеры, //И если на каком-то из них есть сервер, он даст о себе знать //Так же мы будем ждать сервер, если не можем его найти public void FindServer() { //Данные, которые мы будем рассылать в широковещательном UDP сообщении //Будем отсылвать 1 байт, просто потому что. В этом нет какой-то логики //Можем не отсылать данных вообще. //Так же в эту же переменнаю будут записаны данные, которые мы получим от сервера. //А именно - TCP порт сервера var data = new byte[] { 1 }; //Сервер, если он есть в локальной сети, слушает UDP сообщения на 5000 порту //Потому мы быдем отсылать сообшение всем, на порт 5000 var endPoint = new IPEndPoint(IPAddress.Broadcast, 5000); //Номер попытки нахождения сервера. То есть мы первый раз отправляем сообщение о поиске сервера int tryNum = 1; //Создаем формочку, которая будет отображать пользователю информацию, что мы 1 раз //Пытаемся подключиться к серверу. //Это нужно для того, чтобы в ситуации когда сервера нет, и мы пробуем найти его снова и снова, //Пользователь видел, что программа не висит, и все нормально var placeHolder = new PlaceHolderWrapper($"Finding server try #{tryNum}"); //Сохдаем объект для отправки и приема данных по протоколу UDP //ОС сама выберет порт, на котором будет работать этот клиент, потому не передаем //аргументов в конструктор var udpClient = new UdpClient(); //Устанавливаем, что данный клиент будет ждать сообщений только 1000 милисекунд //Если данных нет в течении 1000 секунд - будет брошено исключение //Сделано для того чтобы мы могли отослать новое сообщение, если на старое никто не ответил //Ведь сервер может быть запущен позже, чем клиент udpClient.Client.ReceiveTimeout = 1000; //Условно бесконечный цикл. Сам цикл будет работать вечно, но внутрянняя логика //Прервет его выполнение в необходимый момент while (true) { //Если код внутри блока try выбросит исключение, выполнение перейдет в блок catch //И мы сможем предпринять какие-то действия, обработать эту ситуацию //В данном случае, мы можем получить исключение времени ожидания, //Понять, что переходим на следующую итерацию, уведомить про это пользователя, //И послать новое сообщение try { //Отправляем сообщение длиной в 1 байт всем пк на порт 5000 udpClient.Send(data, data.Length, endPoint); //Ждем, когда сервер вернет нам свой порт. //Если сервер прислал порт, он будет записан в массив data в виде 4-х байт //В переменную endPoint запишется адресс сервера, откуда нам пришло сообщение //Это и есть адрес сервера. Ведь он отправит нам ответ data = udpClient.Receive(ref endPoint); //заканчиваем цикл while, мы получили TCP порт, так что пора к нему присоединяться break; } //В течении секунды не пришло сообщения catch { //Увеличиваем счетчик попыток на 1 tryNum++; //У нашей формы заглушки устанавливаем новый текст для отображения //Так, при каждой попытке мы увидим на консоли ее номер placeHolder.Content = $"Finding server try #{tryNum}"; } } //Отчищаем UDP клиента, он нам больше не понадобится //метод Dispose освободит занятый порт udpClient.Dispose(); //Получаем число, порт сервера, из байт, которые он нам прислал //Чило, а именно порт сервера, хранится в переменной типв=а int //Допустим, порт сервера это 5100 //По сети могут быть переданы только байты, потому данные биты (нули и единицы) //Разбиваются на 4 байта. Почему 4? int занимает 32 бита //А один байт занимает 8 бит. Соответственно любое число типа int может быть разбито на 4 байта //Нам же надо склеить эти байты обратно в int переменнную //BitConverter умеет отдавать байты для конкретного числа и создавать число из байт. //Смело пользуемся им int targetPort = BitConverter.ToInt32(data, 0); //Устанавливаем соединение с сервером. его IP адрес мы получили при получении UDP сообщения tcpClient.Connect(endPoint.Address, targetPort); //Запускаем метод ListenConnectioin, этот метод будет слушать данные от сервера, и вызывать //Событие о том, что пришел какой-то отсет от сервера. Все, кто захотят об этом узнать - узнают Task.Factory.StartNew(ListenConnection); }
private void Connect(string name, string ip, int port) { header = 0; client = new TcpClient(); // Client connects to the server on the specified ip and port. try { client.Connect(ip, port); } catch (ArgumentNullException e) { Console.WriteLine(e.Message + "\n" + e.StackTrace); MessageBoxResult mbr = MessageBox.Show("IP was empty."); return; throw; } catch (ArgumentOutOfRangeException e) { Console.WriteLine(e.Message + "\n" + e.StackTrace); MessageBoxResult mbr = MessageBox.Show("Port isn't within the allowed range."); return; throw; } catch (SocketException e) { Console.WriteLine(e.Message + "\n" + e.StackTrace); MessageBoxResult mbr = MessageBox.Show("Couldn't access the socket."); return; throw; } catch (ObjectDisposedException e) { Console.WriteLine(e.Message + "\n" + e.StackTrace); MessageBoxResult mbr = MessageBox.Show("TCP Client is closed."); return; throw; } this.Dispatcher.Invoke(() => { btn_connect.IsEnabled = false; btn_disconnect.IsEnabled = true; }); // Get client stream for reading and writing. // Using is a try finally, if an exception occurs it disposes of the stream. using (NetworkStream stream = client.GetStream()) { Send(stream, name, header); while (true) { if (client.Connected) { Receive(stream); } else { stream.Dispose(); client.Close(); client.Dispose(); Thread.CurrentThread.Join(); } } }; }
public void ConnectToServer() { clientSocket = new TcpClient(); clientSocket.Connect("127.0.0.1", 9999); stream = clientSocket.GetStream(); }
public void InitializeConnection(string IP, string User) { _user = User; IPAddress ipAddress = IPAddress.Parse(IP); byte[] response; byte[] answer; // Check if IP is reachable bool check = checkIfServerIsReachable(ipAddress); if (check == false) { throw new Exception("Server ist zur Zeit nicht erreichbar!"); } // erstmal verbinden try { _tcpServer = new TcpClient(); _tcpServer.Connect(ipAddress, _port); } catch (Exception) { _tcpServer = null; throw new Exception("Server ist zur Zeit nicht erreichbar! (Antwortet nicht auf Anfragen)"); } _swSender = new BinaryWriter(_tcpServer.GetStream()); _srReceiver = new BinaryReader(_tcpServer.GetStream()); // sende meinen public key zum server byte[] myPubKey = Converter.fromStringToByteArray(_clientEncryption.getPublicKey()); sendMessage(myPubKey); // empfange rij key + iv vom server (verschlüsselt mit meinem pub key) Int32 length; length = _srReceiver.ReadInt32(); response = new byte[length]; response = _srReceiver.ReadBytes(length); byte[] rijKey = _clientEncryption.DecryptRSA(response); length = _srReceiver.ReadInt32(); response = new byte[length]; response = _srReceiver.ReadBytes(length); byte[] rijIV = _clientEncryption.DecryptRSA(response); // setup rij für spätere kommunikation _clientEncryption.setUpRijndael(rijKey, rijIV); // sende chatmessage klasse mit signature, usernamen und willkommensnachricht Library.Chatmessage message = new Library.Chatmessage(); message.Transmitter = User; message.Message = "Welcome"; message.MessageType = Library.Chatmessage.MESSAGE_TYPE_CONNECT; message.OperatingSystem = Environment.OSVersion; answer = _clientEncryption.EncryptRijndael(Converter.fromObjectToByteArray(message)); sendMessage(answer); _thrMessaging = new Thread(new ThreadStart(ReceiveMessages)); _thrMessaging.IsBackground = true; _thrMessaging.Start(); connected = true; }
public void ConnectToServer() { client = new TcpClient(); client.Connect(Host, Port); }
/// <summary> /// Starts this session /// </summary> public void Start() { // initilaize the tcp end point IPEndPoint ep = new IPEndPoint(IPAddress.Parse(ConfigurationManager.AppSettings[0]), int.Parse(ConfigurationManager.AppSettings[1])); string answer = ""; string msg; string commandLine = ""; while (true) { // connect to the server TcpClient client = new TcpClient(); client.Connect(ep); Console.WriteLine("You are connected"); _stream = client.GetStream(); _reader = new MessageReader(new StreamReader(_stream)); _writer = new MessageWriter(new StreamWriter(_stream)); Task write = null; // task for read answers from the server Task read = new Task(() => { do { answer = _reader.ReadMessage(); try { // check if it's a move Move move = Move.FromJson(answer); if (move.ClientId != clientId) { Console.WriteLine(move.ToString()); } } catch { if (!answer.Contains("close")) { Console.WriteLine(answer); } // if game end else { Console.WriteLine("Game ended!"); } // if it's not multiple game break if (!CheckIfMultiple(commandLine, answer)) { break; } } } while (!answer.Contains("close")); }); // task for write a command to the server write = new Task(() => { while (true) { commandLine = Console.ReadLine(); _writer.WriteMessage(commandLine); } }); write.Start(); read.Start(); // wait to answer from server read.Wait(); _stream.Close(); _reader.Close(); _writer.Close(); client.Close(); } }