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
| public void ConnectToServer(string ServerName)
{
if (this.SocketClient == null || !this.SocketClient.Connected)
{
this.SocketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress[] ipadress;
//On récupere les informations du serveur (son nom puis son adresse IP)
IPHostEntry he = Dns.GetHostByName(ServerName);
ipadress = he.AddressList;
this.SocketClient.BeginConnect(new IPEndPoint(ipadress[0], 1001), new AsyncCallback(ConnectCallback), null);
}
else
{
//on affiche un message
MessageBox.Show("Déjà connecté à un serveur");
}
}
/// Fonction de rappel pour la connection
/// <param name="asyncResult">un objet IAsyncResult</param>
private void ConnectCallback(IAsyncResult asyncResult)
{
try
{
//on récupere le socket sur lequel la connexion doit avoir lieu
Socket socket = (Socket)asyncResult.AsyncState;
//On affect SocketClient au socket de connection
this.SocketClient = socket;
//on met fin à la demande de connection
socket.EndConnect(asyncResult);
//on affiche un message
DisplayMessage("Connecté à un serveur");
this.LocalsocketClientIsShutingDown = false;
// On initie une lecture
this.SocketClient.BeginReceive(this.readbuf, 0, this.readbuf.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), null);
}
catch (SocketException ex)
{
DisplayMessage(ex.Message);
}
} |
Partager