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 Serwer_ECHO
- {
- class Program
- {
- static void Main(string[] args)
- {
- bool tryAgain = true;
- byte[] data = new byte[1024];
- string input, stringData;
- Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
- while (tryAgain)
- {
- Console.Write("Which port you want to create server [7]? : ");
- string port = Console.ReadLine(); if (port == "") port = "7";
- try
- {
- IPAddress ipAd = IPAddress.Parse("127.0.0.1");
- TcpListener listen = new TcpListener(ipAd, int.Parse(port));
- listen.Start();
- Console.WriteLine("The local Endpoint is : " + listen.LocalEndpoint);
- Console.WriteLine("Waiting for connection...");
- tryAgain = false;
- socket = listen.AcceptSocket();
- String message;
- Console.WriteLine("Connection accepted from " + socket.RemoteEndPoint);
- while (true)
- {
- int k = socket.Receive(data);
- if (k == 0) break; // jeżeli wysłano pusty pakiet
- else
- {
- message = Encoding.ASCII.GetString(data, 0, k);
- if (message.Equals("App:CloseConnection", StringComparison.InvariantCultureIgnoreCase)) break; // jeżeli wysłano komende zamkniecia polaczenia
- Console.WriteLine(message);
- StringBuilder res = new StringBuilder();
- res.Append(message);
- byte[] buffer = Encoding.ASCII.GetBytes(res.ToString());
- socket.Send(buffer);
- }
- }
- Console.WriteLine("\nClient has disconnected from server");
- socket.Close();
- listen.Stop();
- Console.ReadLine();
- }
- catch (FormatException e)
- {
- Console.Write("Unable to create server or port is not number, 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 (SocketException e)
- {
- Console.WriteLine("Client has closed connection unproperly");
- Console.WriteLine("or server has another instance running on this port.");
- Console.ReadLine();
- }
- } //while (tryAgain)
- } // main
- } // class
- } // namespace
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement