1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace Zappy.DLL
{
/// <summary>
/// Classe gérant les socket simplement
/// </summary>
class Sock
{
private string error;
private IPAddress ip;
private Socket socket;
/// <summary>
/// Constructeur de la classe Sock.
/// </summary>
/// <param name="addr">Adresse Ip du serveur</param>
/// <param name="port">Port d'écoute du serveur</param>
public Sock(string addr, int port)
{
ip = IPAddress.Parse(addr);
this.socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
socket.Connect(new IPEndPoint(ip, port));
}
catch (SocketException E)
{
this.error = E.Message;
}
}
/// <summary>
/// Fonction permettant de récupérer ce qu'il y a sur la socket
/// </summary>
/// <returns>retourne la valeur lue sur la socket</returns>
public string Receive()
{
byte[] msg = new Byte[256];
int nb = 0;
string ret = "";
try
{
do
{
nb = this.socket.Receive(msg);
ret += Encoding.ASCII.GetString(msg, 0, nb);
}
while (nb > 0);
}
catch (Exception E)
{
this.error = E.Message;
}
return (ret);
}
/* GETTERS / SETTERS */
/// <summary>
/// Retourne VRAI si une erreur est survenue
/// </summary>
public bool isError
{
get { return (this.error.Length > 0); }
}
/// <summary>
/// Retourne la dernière erreur et la supprime
/// </summary>
public string Error
{
get
{
string ret = this.error;
this.error = "";
return (this.error);
}
}
/// <summary>
/// Retourne VRAI si la socket est connectée
/// </summary>
public bool Connected
{
get { return (this.socket.Connected); }
}
}
} |