Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Text;
- using System.Net.Sockets;
- using System.Net;
- namespace Klient_ECHO
- {
- class Program
- {
- public static void closeConnection(Socket socket)
- {
- Console.WriteLine("Disconnected from server...");
- socket.Shutdown(SocketShutdown.Both);
- socket.Close();
- }
- public static void tryConnection(Socket socket)
- {
- bool tryAgain = true;
- while (tryAgain)
- {
- Console.Write("Which port you want to connect [7]? : ");
- string port = Console.ReadLine(); if (port == "") port = "7";
- try
- {
- IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), int.Parse(port));
- try
- {
- socket.Connect(ipep);
- Console.WriteLine("Connected to " + ipep.ToString());
- tryAgain = false;
- }
- catch (SocketException e)
- {
- Console.Write("Unable to connect to server, want to try with another port? [y/n]: ");
- string ca = Console.ReadLine();
- if (ca.ToLower() == "y" || ca.ToLower() == "yes") tryAgain = true;
- else tryAgain = false;
- }
- }
- catch (FormatException e)
- {
- Console.WriteLine("This is not a number, try again.");
- }
- }
- }
- static void Main(string[] args)
- {
- byte[] data = new byte[1024];
- string input, stringData;
- Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
- tryConnection(socket);
- int recv = 0;
- stringData = Encoding.ASCII.GetString(data, 0, recv);
- Console.WriteLine(stringData);
- while (true)
- {
- input = Console.ReadLine();
- if (input == "close") break;
- else
- {
- socket.Send(Encoding.ASCII.GetBytes(input));
- data = new byte[1024];
- recv = socket.Receive(data);
- stringData = Encoding.ASCII.GetString(data, 0, recv);
- Console.WriteLine("Reply from server: " + stringData);
- }
- }
- closeConnection(socket);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement