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
|
class C_Mysocket
{
//Classe socket local perso
private int port;
Socket listensock;
Socket activesock;
IPEndPoint endpt;
byte[] buff;
/*** Fonctions membres ***/
public C_Mysocket(int _port)
{
port = _port;
}
public int Start()
{
try
{
//Ouverture du socket sur l'adresse locale et le port demandé
listensock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPHostEntry hostadr = Dns.GetHostEntry(Dns.GetHostName());
endpt = new IPEndPoint(hostadr.AddressList[0], port);
//Bind à un port , écoute sur ce port et démarre le thread asynchrone
listensock.Bind(endpt);
listensock.Listen(1);
//debut asynchrone - démarrage du thread d'accept | attente de la connection
listensock.BeginAccept(new AsyncCallback(connexionAcceptCallback), listensock);
return port;
}
catch (Exception se)
{
MessageBox.Show("Start method error message : "+ se.Message);
return 0;
}
}
void connexionAcceptCallback(IAsyncResult asyncResult)
{
try
{
activesock = listensock.EndAccept(asyncResult);
activesock.BeginReceive(buff, 0, buff.Length, SocketFlags.None, receiveCallback, activesock);
}
catch (Exception se)
{
MessageBox.Show(se.Message);
}
}
...
public void Send(string s)
{
try
{
buff = ASCIIEncoding.ASCII.GetBytes(s);
activesock.BeginSend(buff, 0, buff.Length, SocketFlags.None, new AsyncCallback(this.sendCallback), activesock);
}
catch (Exception se)
{
MessageBox.Show(se.Message);
}
}
private void sendCallback(IAsyncResult asyncResult)
{
int send = activesock.EndSend(asyncResult);
}
.. |
Partager