Tutorial para aprender a programar un socket de cliente en C#
Solo copia y pega el codigo de abajo en un archivo .cs.
public byte[] EnviarMensaje(byte[] comando){
string ip="127.0.0.1"; // ojo con la ip
string puerto=8080; // ojo con el puerto
byte[] bytes = new byte[4024];
byte[] bytesRecv;
Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
sender.Connect(ip, puerto);
Console.WriteLine("Socket connected to {0}",
sender.RemoteEndPoint.ToString());
int bytesSent = sender.Send(comando);
int bytesRec = sender.Receive(bytes);
Console.WriteLine("Echoed test = {0}",
bytesRecv = Utils.Asc2Bytes(Encoding.ASCII.GetString(bytes, 0, bytesRec)));
sender.Shutdown(SocketShutdown.Both);
sender.Close();
}
catch (TimeoutException ex)
{
throw new OperationException(-1, "El servidor no responde");
}
catch (SocketException ex)
{
throw new OperationException(-1, "Hmmmm, parece ser que hay un error de comunicacion");
}
catch (CommunicationException ex)
{
throw new OperationException(-1, "Hay un error de comunicacion con el servidor ");
}
catch (Exception e)
{
throw new Exception("Excepcion inesperada");
}
return bytesRecv;
}
3 questions
Ask a question As anonymous6285aa96ac601:
easy
👌
👌