private void btncn_Click(object sender, EventArgs e) { ipServer = new IPEndPoint(IPAddress.Parse("192.168.1.110"), 1234); client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); client.Connect(ipServer); }
private void SendMessageFromSocket(object port) { try { // Буфер для входящих данных byte[] bytes = new byte[1024]; // Соединяемся с удаленным устройством // Устанавливаем удаленную точку для сокета IPHostEntry ipHost = Dns.GetHostEntry("localhost"); IPAddress ipAddr = ipHost.AddressList[0]; IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, (int)port); Socket sender = new Socket(ipAddr.AddressFamily, SocketType.Stream, ProtocolType.Tcp); // Соединяем сокет с удаленной точкой sender.Connect(ipEndPoint); string request = ""; Dispatcher.Invoke(() => { request = indexTextBox.Text; indexTextBox.Text = string.Empty; }); byte[] msg = Encoding.UTF8.GetBytes(request); // Отправляем данные через сокет int bytesSent = sender.Send(msg); // Получаем ответ от сервера int bytesRec = sender.Receive(bytes); string str = Encoding.UTF8.GetString(bytes, 0, bytesRec); for (int i = 0; i < str.Length; i++) { if (str[i] == '.') { str = str.Insert(i + 1, ", "); } } Dispatcher.Invoke(() => { streetTextBox.Text = str; }); // Освобождаем сокет sender.Shutdown(SocketShutdown.Both); sender.Close(); } catch (SocketException ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error); } catch (ArgumentNullException ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error); } }
public void EstablishConnection() { _sender.Connect(_localEndPoint); }
static void Main(string[] args) { #if NETCOREAPP3_X Console.WriteLine(RuntimeInformation.OSArchitecture.ToString()); Console.WriteLine(RuntimeInformation.OSDescription); Console.WriteLine(RuntimeInformation.FrameworkDescription); #endif Console.Title = "Client"; int port = 18180; Console.WriteLine("Please input port to connect ..."); if ( int.TryParse ( Console.ReadLine() , out int p ) ) { port = p; } Console.WriteLine($"Connect Port: {port}"); IPAddress ipa; IPAddress.TryParse("127.0.0.1", out ipa); var socket = new Socket ( AddressFamily.InterNetwork , SocketType.Stream , ProtocolType.Tcp ); var ipep = new IPEndPoint(ipa, port); socket.Connect(ipep); //Console.ReadLine(); var handler = new SocketAsyncDataHandler <string> ( socket , 1 ); var sendEncoding = Encoding.UTF8; var receiveEncoding = Encoding.UTF8; handler .StartReceiveWholeDataPackets ( 4 , 0 , 4 , () => { var saea = new SocketAsyncEventArgs(); saea.SetBuffer ( new byte[64 * 1024] , 0 , 64 * 1024 ); return(saea); } , (x, y, z, w) => { var offset = 4; var l = y.Length - z; #if NETCOREAPP3_X var buffer = new ReadOnlySpan <byte>(y, offset, l); #else var buffer = new byte[l]; Buffer .BlockCopy ( y , offset , buffer , 0 , l ); #endif var s = receiveEncoding.GetString(buffer); //Console.WriteLine("SocketID: {1}{0}Length: {2}{0}Data: {2}", "\r\n", x.SocketID, y.Length ,s); Console.Write(s); return(true); } ); string input = string.Empty; while ((input = Console.ReadLine()) != "q") { try { var buffer = sendEncoding.GetBytes(input); var l = buffer.Length; byte[] intBytes = BytesHelper.GetLengthHeaderBytes(buffer); handler.SendDataSync(intBytes); handler.SendDataSync(buffer); Console.WriteLine("Sended"); } catch (Exception e) { Console.WriteLine(e.ToString()); } } }
//Method to login and connect to server public bool connect() { TextBox userName = Application.OpenForms["Form1"].Controls["textBox1"] as TextBox; TextBox password = Application.OpenForms["Form1"].Controls["textBox2"] as TextBox; TextBox txtServerIP = Application.OpenForms["Form1"].Controls["txtServerIP"] as TextBox; TextBox txtServerPort = Application.OpenForms["Form1"].Controls["txtServerPort"] as TextBox; if (oneTime) { IPAddress host = IPAddress.Parse(txtServerIP.Text);////161.45.167.244"); IPEndPoint hostep = new IPEndPoint(host, Int32.Parse(txtServerPort.Text)); sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); sock.Connect(hostep); oneTime = false; } string UnamePassword = userName.Text + ";_;" + password.Text; byte[] msg = Encoding.ASCII.GetBytes(UnamePassword); byte[] reply = new byte[5]; // Send the data through the socket. int bytesSent = sock.Send(msg); sock.Receive(reply); //MessageBox.Show(System.Text.Encoding.ASCII.GetString(reply)); //Socket1 = new TcpClient(); //Socket1.Connect("10.1.10.136", 3000); //NetworkStream strm = Socket1.GetStream(); //ASCIIEncoding uname = new ASCIIEncoding(); //ASCIIEncoding size = new ASCIIEncoding(); //string UnamePassword=userName.Text+";_;"+password.Text; //byte[] msg = uname.GetBytes(UnamePassword); //var length = msg.Length.ToString(); ////string lengthOfMessage; //strm.Write(size.GetBytes(length), 0, size.GetBytes(length).Length); //strm.Write(msg, 0, msg.Length); //strm.se //Socket.Available string k = System.Text.Encoding.ASCII.GetString(reply, 0, 5); int result = 0; if (k.Contains("true")) { result = Int32.Parse(k.Substring(4, 1)); k = "true"; } if (bool.Parse(k)) { if (result == 1) { MessageBox.Show("User Didn't exist, Login has been created with credentials entered"); } uName = userName.Text; return(true); } else { loginCount++; if (loginCount == 3) { MessageBox.Show("Limit(3 times) for wrong password reached."); //sock.Close(); Environment.Exit(0); oneTime = true; } return(false); } //return bool.Parse(reply.ToString()); }
// Function to get the score of every player from the server public List <Player> GetScoreAllPlayers() { List <Player> players = new List <Player>(); // Data buffer for incoming data. byte[] bytes = new byte[1024]; // Connect to a remote device. try { var address = Dns.GetHostEntry(serverAddress).AddressList.First(ip => ip.AddressFamily == AddressFamily.InterNetworkV6); // IPV4 to IPV6 address IPAddress ipAddress = address; IPEndPoint remoteEP = new IPEndPoint(ipAddress, Int32.Parse(serverPort)); // Create a TCP/IP socket. Socket sender = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp); // Connect the socket to the remote endpoint. Catch any errors. try { sender.Connect(remoteEP); // Encode the data string into a byte array. byte[] msg = Encoding.ASCII.GetBytes("<ScorePlayers>" + this.id);// Ask the score of other players // Send the data through the socket. int bytesSent = sender.Send(msg); // Receive the response from the remote device. int bytesRec = sender.Receive(bytes); string result = Encoding.ASCII.GetString(bytes, 0, bytesRec); if (result.IndexOf("<ReturnScorePlayers>") < 0) { Console.WriteLine("Server return error."); } // Release the socket. sender.Shutdown(SocketShutdown.Both); sender.Close(); // Get the answer of the server and put it on the List of players score result = result.Replace("<ReturnScorePlayers>", ""); string[] result_array = result.Split(';'); for (int i = 0; i < result_array.Length; i += 2) { players.Add(new Player(result_array[i], Int16.Parse(result_array[i + 1])));// Create a new player with its id and score and add it to the list of all players } return(players); } catch (Exception e) { Console.WriteLine("Unexpected exception : {0}", e.ToString()); } } catch (Exception e) { Console.WriteLine(e.ToString()); } return(null); }