Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.IO;
- using System.Net;
- using System.Net.Sockets;
- using System.Text;
- using System.Threading;
- namespace SocketExample
- {
- class MainClass
- {
- public static void Main(string[] args)
- {
- new Thread(MainClass.Servidor)
- .Start();
- Thread.Sleep(1000);
- new Thread(MainClass.Cliente)
- .Start();
- }
- public static void Servidor()
- {
- IPHostEntry datosAnfitrion = Dns.GetHostEntry(Dns.GetHostName());
- IPAddress direccionIP = datosAnfitrion.AddressList[0];
- IPEndPoint puntoFinal = new IPEndPoint(direccionIP, 11000);
- Socket escuchador = new Socket(
- direccionIP.AddressFamily,
- SocketType.Stream,
- ProtocolType.Tcp
- );
- escuchador.Bind(puntoFinal);
- escuchador.Listen(10);
- while (true)
- {
- Console.WriteLine("Esperando conexión...");
- Socket socket = escuchador.Accept();
- Console.WriteLine("Conexión establecida! Enviando...");
- FileStream archivo = null;
- switch (".jpg")
- {
- case ".jpg":
- archivo = File.OpenWrite("recibido.jpg");
- break;
- case ".txt":
- archivo = File.OpenWrite("recibido.txt");
- break;
- }
- byte[] buffer = new byte[1024];
- int leidos = 0;
- while ((leidos = socket.Receive(buffer)) > 0) {
- archivo.Write(buffer, 0, leidos);
- }
- archivo.Close();
- Console.WriteLine("Listo!");
- socket.Shutdown(SocketShutdown.Both);
- socket.Close();
- }
- }
- public static void Cliente()
- {
- IPHostEntry datosAnfitrion = Dns.GetHostEntry(Dns.GetHostName());
- IPAddress direccionIP = datosAnfitrion.AddressList[0];
- IPEndPoint puntoFinal = new IPEndPoint(direccionIP, 11000);
- while (true)
- {
- Socket socket = new Socket(
- direccionIP.AddressFamily,
- SocketType.Stream,
- ProtocolType.Tcp
- );
- socket.Connect(puntoFinal);
- socket.SendFile("archivo.jpg");
- socket.Close();
- Thread.Sleep(10000);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement