Ac谩 va un ejemplo sencillo de un tcplistener聽 en C# modo consola a pedido de Matias – el negro 馃檪
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Sockets;
namespace tcplistener_console
{
聽聽聽 class Program
聽聽聽 {
聽聽聽聽聽聽聽 static int Main(string[] args)
聽聽聽聽聽聽聽 {
聽聽聽聽聽聽聽聽聽聽聽 Console.Write(“tcplistener by hvivani – 20110225 – para el negro: \r\n”);
聽聽聽聽聽聽聽聽聽聽聽 if (args.Length == 0)
聽聽聽聽聽聽聽聽聽聽聽 {
聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽 System.Console.WriteLine(“Parametros: Puerto IP 聽 \r\n”);
聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽 System.Console.WriteLine(“Ejemplo: tcplistener 2525 127.0.0.1聽 \r\n”);
聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽 System.Console.WriteLine(“si tenes mas de una interfaz de red, usa la ip de dicha interfaz.聽 \r\n”);
聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽 return 1;
聽聽聽聽聽聽聽聽聽聽聽 }
聽聽聽聽聽聽聽聽聽聽聽 TcpListener server = null;
聽聽聽聽聽聽聽聽聽聽聽 // Set the TcpListener on port.
聽聽聽聽聽聽聽聽聽聽聽 Int32 port = int.Parse(args[0]);
聽聽聽聽聽聽聽聽聽聽聽 IPAddress localAddr = IPAddress.Parse(args[1]);
聽聽聽聽聽聽聽聽聽聽聽 // TcpListener server = new TcpListener(port);
聽聽聽聽聽聽聽聽聽聽聽 server = new TcpListener(localAddr, port);
聽聽聽聽聽聽聽聽聽聽聽 // Start listening for client requests.
聽聽聽聽聽聽聽聽聽聽聽 server.Start();
聽聽聽聽聽聽聽聽聽聽聽 // Buffer for reading data
聽聽聽聽聽聽聽聽聽聽聽 Byte[] bytes = new Byte[256];
聽聽聽聽聽聽聽聽聽聽聽 String data = null;
聽聽聽聽聽聽聽聽聽聽聽 // Enter the listening loop.
聽聽聽聽聽聽聽聽聽聽聽 while (true)
聽聽聽聽聽聽聽聽聽聽聽 {
聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽 Console.Write(“Waiting for a connection… “);
聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽 // Perform a blocking call to accept requests.
聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽 // You could also user server.AcceptSocket() here.
聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽 TcpClient client = server.AcceptTcpClient();
聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽 Console.WriteLine(“Connected!”);
聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽 data = null;
聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽 // 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 ASCII string.
聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽 data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽 Console.WriteLine(“Received: {0}”, data);
聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽 // Process the data sent by the client.
聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽 data = data.ToUpper();
聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽 byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽 // Send back a response.
聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽 //stream.Write(msg, 0, msg.Length);
聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽 //Console.WriteLine(“Sent: {0}”, data);
聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽 }
聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽 // Shutdown and end connection
聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽 client.Close();
聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽 }
聽聽聽聽聽聽聽 }聽
聽聽聽 }
}