Bonsoir,
Je cherche mais je n'arrive pas à trouver un moyen pour que la taille de mon tableau "ReceivedData" soit égale au nombre de byte du paquet reçu afin de ne pas initialiser avec une valeur par défaut mon tableau, voici les codes :
Partie Client :
public class SocketClientChat
{
public string IpAdress { get; set; }
public int Port { get; set; }
public byte[] DataBuffer { get; set; }
public Socket Client { get; set; }
public SocketClientChat(string ipAdress, int port)
{
this.IpAdress = ipAdress;
this.Port = port;
this.Client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
}
public void SendMessage(string message)
{
this.Client.Connect(IPAddress.Parse(this.IpAdress), this.Port);
int byteCount = Encoding.ASCII.GetByteCount(message);
this.DataBuffer = new byte[byteCount];
this.DataBuffer = Encoding.ASCII.GetBytes(message);
this.Client.Send(this.DataBuffer);
this.Client.Close();
}
}
Partie Serveur :
public class SocketServerChat
{
public string IpAdress { get; set; }
public int Port { get; set; }
public byte[] ReceivedData { get; set; }
public IPEndPoint IPEndPoint { get; set; }
public StringBuilder Message { get; set; }
public NetworkStream NetworkStream { get; set; }
public Socket Client { get; set; }
public Socket Server { get; set; }
public SocketServerChat(string ipAdress, int port)
{
this.IpAdress = ipAdress;
this.Port = port;
this.Message = new StringBuilder();
this.IPEndPoint = new IPEndPoint(IPAddress.Parse(this.IpAdress), this.Port);
this.Server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
}
public void OpenServer()
{
try
{
this.Server.Bind(this.IPEndPoint);
this.Server.Listen(0);
Console.WriteLine("Server started...\n");
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
public void ReadStreamNetwork()
{
while (true)
{
this.Message.Clear();
this.ReceivedData = new byte[100];
this.Client = this.Server.Accept();
this.Client.Receive(this.ReceivedData);
foreach (byte data in this.ReceivedData)
{
if (data.Equals(00))
break;
else
this.Message.Append(Convert.ToChar(data));
}
Console.WriteLine($"Date : [{DateTime.Now}] || Message : {this.Message.ToString()} || Taille du message : {this.Message.Length}");
}
}
}
Ps: C'est ma première utilisation des sockets si vous avez des conseils ou autres trucs par rapport au socket je suis preneur :D