morpionReseau/go01/socketPlateau.cs

314 lines
11 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Threading;
using System.Net.NetworkInformation;
namespace go01
{
public class socketPlateau
{
#region enum
public enum TypeSocket_E { NONE, Serveur, Client, LAST }
public enum commande_E { Join, Leave, Place, Win, WhoTurn, LAST } // ConfigGo_S ; null ; Point ; Goban.PlayerTuen(string) ; Goban.Joueur_E(Tour)
#endregion
#region struct
[Serializable]
public struct CommandeSocket_S
{
public commande_E commande;
public object data;
public CommandeSocket_S(commande_E cmd, object dt)
{
commande = cmd;
data = dt;
}
}
[Serializable]
public struct ConfigGo_S
{
private string uid;
public string Uid { get { return uid; } }
private string partName;
public string PartName { get { return partName; } }
public string NomJoeurClient;
private string nomJoeurServeur;
public string NomJoeurServeur { get { return nomJoeurServeur; } }
private int taille;
public int Taille { get { return taille; } }
private int pionaAligner;
public int PionAligner { get { return pionaAligner; } }
private IPAddress ipServeur;
public IPAddress IpServeur { get => ipServeur; }
public readonly int port;
public ConfigGo_S(string Uid, string PartName, string NomJoeurClient, string NomJoeurServeur, int Taille, int PionaAligner, IPAddress ipServeur, int port)
{
this.uid = Uid;
this.partName = PartName;
this.NomJoeurClient = NomJoeurClient;
this.nomJoeurServeur = NomJoeurServeur;
this.taille = Taille;
this.pionaAligner = PionaAligner;
this.ipServeur = ipServeur;
this.port = port;
}
public override string ToString()
{
return partName;
}
public static implicit operator string(ConfigGo_S part)
{
return part.ToString();
}
}
#endregion
#region variable
private Socket socServ, socCli;
private Socket SocCli
{
get
{
if(socFlag == TypeSocket_E.Serveur && socCli != null || socFlag == TypeSocket_E.Client)
{
return socCli;
}
else
{
return null;
}
}
set
{
socCli = value;
}
}
private TypeSocket_E socFlag = 0;
IPAddress adresseIpCourante;
int port;
private static Boolean connexionEtablie = false;
System.Threading.Timer timerBroadcast;
Goban plateauDeJeu;
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
ConfigGo_S cfgGo;
#endregion
#region event
public delegate void OnJoinServ(object myObject, socketPlateauServArgs myArgs);
public event OnJoinServ onJoinServ;
#endregion
public socketPlateau(TypeSocket_E socF, ConfigGo_S cfgGo, Goban g)
{
plateauDeJeu = g;
adresseIpCourante = cfgGo.IpServeur;
socFlag = socF;
this.port = cfgGo.port;
this.cfgGo = cfgGo;
if(socFlag == TypeSocket_E.Client)
{
socFlag = TypeSocket_E.Client;
try
{
socCli = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//socCli.Blocking = false;
//IPAddress IPDist = Verifier(cfgGo.IpServeur.ToString());
socCli.BeginConnect(new IPEndPoint(cfgGo.IpServeur, port), new AsyncCallback(SurConnection), socCli);
}
catch (Exception ee)
{
//controle(true);
MessageBox.Show("Connexion impossible : " + ee.Message);
}
}
else if(socFlag == TypeSocket_E.Serveur)
{
//AttenteJoueur();
}
}
#region serveur
public void AttenteJoueur()
{
if (socFlag != TypeSocket_E.Serveur)
return;
var startTimeSpan = TimeSpan.Zero;
var periodTimeSpan = TimeSpan.FromSeconds(5);
timerBroadcast = new System.Threading.Timer((ee) =>
{
broadcast();
}, null, startTimeSpan, periodTimeSpan);
socFlag = TypeSocket_E.Serveur;
socServ = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socServ.Bind(new IPEndPoint(adresseIpCourante, port));
socServ.Listen(1);
socServ.BeginAccept(new AsyncCallback(SurDemandeDeCo), socServ);
}
private void SurDemandeDeCo(IAsyncResult iAR)
{
if (socFlag == TypeSocket_E.Serveur && !socketPlateau.connexionEtablie)
{
Socket sTmp = (Socket)iAR.AsyncState;
socCli = sTmp.EndAccept(iAR);
#if DEBUG
Console.WriteLine($"Connexion effectuée par {((IPEndPoint)socCli.RemoteEndPoint).Address}");
#endif
connexionEtablie = true;
timerBroadcast.Dispose();
InitialiserReception(socCli);
}
else if(socFlag == TypeSocket_E.Serveur && socketPlateau.connexionEtablie)
{
Socket sTmp = (Socket)iAR.AsyncState;
socCli = sTmp.EndAccept(iAR);
socCli.Send(Encoding.Unicode.GetBytes("Serveur en cours de partie !"));
socCli.Close();
}
}
private void broadcast()
{
if (socFlag != TypeSocket_E.Serveur)
return;
var Client = new UdpClient();
using (MemoryStream ms = new MemoryStream())
{
binaryFormatter.Serialize(ms, cfgGo);
Client.EnableBroadcast = true;
byte[] RequestData = ms.ToArray();
Client.Send(RequestData, RequestData.Length, new IPEndPoint(IPAddress.Broadcast, 8888));
}
// byte[] RequestData = { }; /*= Encoding.ASCII.GetBytes($"{cfgGo.Uid};{cfgGo.PartName};{cfgGo.NomJoeurAdverse};{cfgGo.Taille};{cfgGo.PionaAligner}");*/;
Client.Close();
}
#endregion
#region client
public void rejoindrePartie(IPAddress IPServeur, int port)
{
socFlag = TypeSocket_E.Client;
try
{
socCli = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress IPDist = IPServeur;
socCli.BeginConnect(new IPEndPoint(IPDist, port), new AsyncCallback(SurConnection), socCli);
}
catch (Exception ee)
{
MessageBox.Show("Connexion impossible : " + ee.Message);
}
}
private void SurConnection(IAsyncResult iAR)
{
Socket sTmp = (Socket)iAR.AsyncState;
if (sTmp.Connected) { connexionEtablie = true; InitialiserReception(sTmp); senCmd(new CommandeSocket_S(commande_E.Join, cfgGo)); }
else { MessageBox.Show("Serveur innacessible"); }
}
#endregion
#region commun
private void InitialiserReception(Socket sArg)
{
try
{
var netStream = new NetworkStream(sArg, true);
var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
CommandeSocket_S cmd = (CommandeSocket_S)binaryFormatter.Deserialize(netStream);
switch (cmd.commande)
{
case commande_E.Join:
onJoinServ(this, new socketPlateauServArgs((ConfigGo_S)cmd.data));
break;
case commande_E.Leave:
break;
case commande_E.Place:
break;
case commande_E.WhoTurn:
break;
case commande_E.Win:
break;
}
InitialiserReception(sArg);
}
catch (Exception e)
{
Console.WriteLine("Réception imossible : " + e.Message);
}
}
public void senCmd(CommandeSocket_S cmd)
{
var netStream = new NetworkStream(socCli, true);
var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
binaryFormatter.Serialize(netStream, cmd);
}
#endregion
#region outil
public static void net_adapters(ComboBox cb)
{
List<String> values = new List<String>();
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
cb.Items.Add(nic.Name);
}
}
public static IPAddress Verifier(string sAdresse)
{
IPAddress rep = null;
if (sAdresse.Trim().Length > 0)
{
IPAddress[] ipVerifs = Dns.GetHostEntry(sAdresse).AddressList;
for (int i = 0; i < ipVerifs.Length; i++)
{
//rep += ipVerifs[0].ToString();
if (ipVerifs[i].AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
if (ipVerifs[i] != new IPAddress(0X0100007F))
{
Ping pVerif = new Ping();
PingReply pRepon = pVerif.Send(ipVerifs[i]);
if (pRepon.Status == IPStatus.Success)
{
rep = ipVerifs[i];
Console.WriteLine(ipVerifs[i] + "Ping réussi");
break;
}
else
{
Console.WriteLine(ipVerifs[i] + "Ping KO");
}
}
}
}
}
else
{
Console.WriteLine("Renseigner une adresse");
}
return rep;
}
#endregion
}
}