Witam! Czytałem specyfikację tych metod. Dotyczą one klasy Socket. Nie wiem czy dobrze zrozumiałem. BeginReceive blokuje dostęp do socket? Rozumiem, że te funkcje odpalają osobne wątki? Jak mam w klasie obiekt typu byte[] data = new byte[2048], i np mam kilka klientow ( liste obiektow Socket) i każdy z nich może odpalić metodę BeginReceive i jak każdemu podam jako argument moją tablicę "data" to każdy z nich może coś w niej napisać? Czy ona też jest blokowana? Bo jeśli każdy miałby do niej dostęp, w tej samej chwili, to nadpiszą siebie nawzajem. Czyli jak mam kilka klientów, to mam kilka odpalonych watków na BeginReceive?
#region Properties
Socket socket;
public IPAddress Ip
{
get
{
if (socket != null)
{
return ((IPEndPoint)(this.socket.LocalEndPoint)).Address;
}
else return null;
}
}
private byte[] data = new byte[1024];
List<Socket> clients;
public Socket Socket
{
get
{
if (this.socket == null)
{
throw new NullReferenceException("Socket is null");
}
else
{
return this.socket;
}
}
}
public int Port
{
get
{
if (socket != null)
{
return ((IPEndPoint)this.socket.LocalEndPoint).Port;
}
else
return -1;
}
}
public bool Connected
{
get
{
if (this.socket != null)
return this.socket.Connected;
else return false;
}
}
#endregion
#region Constructor
public Server(IPEndPoint ip)
{
this.clients = new List<Socket>();
this.socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
this.socket.Bind(ip);
}
#endregion
#region Public Methods
public void Start()
{
this.socket.Listen(5);
this.socket.BeginAccept(new AsyncCallback(OnSocketAccept), null);
}
#endregion
#region Protected Methods
protected virtual void OnSocketAccept(IAsyncResult result)
{
Socket clientSocket = this.socket.EndAccept(result);
clientSocket.BeginReceive(this.data,0,this.data.Length, SocketFlags.None, new AsyncCallback(OnBeginReceive), clientSocket);
this.clients.Add(clientSocket);
this.socket.BeginAccept(new AsyncCallback(OnSocketAccept), null);
}
protected virtual void OnBeginReceive(IAsyncResult result)
{
int bytesRead = -1;
Socket socket = (Socket)result.AsyncState;
bytesRead = socket.EndReceive(result);
if (bytesRead > 0)
{
Console.Write(this.data);
}
socket.BeginReceive(this.data, 0, this.data.Length, SocketFlags.None, new AsyncCallback(OnBeginReceive), socket);
}
#endregion