Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Server
- {
- public async void Run(int port)
- {
- TcpListener server = null;
- try
- {
- IPAddress localAddr = IPAddress.Parse("127.0.0.1");
- server = new TcpListener(localAddr, port);
- // Start listening for client requests.
- server.Start();
- // Buffer for reading data
- var bytes = new Byte[256];
- // Enter the listening loop.
- while (true)
- {
- RaiseLog("Waiting for a connection... ");
- // Perform a blocking call to accept requests.
- // You could also user server.AcceptSocket() here.
- TcpClient client = await server.AcceptTcpClientAsync();
- RaiseLog("Connected!");
- // Get a stream object for reading and writing
- NetworkStream stream = client.GetStream();
- int i;
- // Loop to receive all the data sent by the client.
- while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
- {
- // Translate data bytes to a UTF8 string.
- string data = Encoding.UTF8.GetString(bytes, 0, i);
- RaiseLog("Received: {0}", data);
- // Process the data sent by the client.
- data = data.ToUpper();
- byte[] msg = Encoding.UTF8.GetBytes(data);
- // Send back a response.
- stream.Write(msg, 0, msg.Length);
- RaiseLog("Sent: {0}", data);
- }
- // Shutdown and end connection
- client.Close();
- }
- }
- catch (SocketException e)
- {
- RaiseLog("SocketException: {0}", e);
- }
- finally
- {
- // Stop listening for new clients.
- if (server != null)
- {
- server.Stop();
- }
- }
- }
- private void RaiseLog(string format, params object[] args)
- {
- var tmp = Log;
- if (tmp != null)
- {
- string s = string.Format(format, args);
- tmp(this, s);
- }
- }
- public event EventHandler<string> Log;
- }
- private static void Main()
- {
- var server = new Server();
- server.Log += (s, e) => Console.WriteLine(e);
- server.Run(port: 145);
- ...
- }
Advertisement
Add Comment
Please, Sign In to add comment