This code is from the server of an application in C #, for example I have 3 clients connected, but I do not know how to do it if I want to send it to the first or third etc. etc.
Someone give me an idea xfa.
%pre%This code is from the server of an application in C #, for example I have 3 clients connected, but I do not know how to do it if I want to send it to the first or third etc. etc.
Someone give me an idea xfa.
%pre%This code is from the server of an application in C #, for example I have 3 clients connected, but I do not know how to do it if I want to send it to the first or third etc. etc.
Someone give me an idea xfa.
private Socket serverSocket;
private Socket clientSocket; // We will only accept one socket.
private byte[] buffer;
public Form1()
{
InitializeComponent();
StartServer();
}
private void StartServer()
{
try
{
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
serverSocket.Bind(new IPEndPoint(IPAddress.Any, 3333));
serverSocket.Listen(10);
serverSocket.BeginAccept(AcceptCallback, null);
}
catch (SocketException ex)
{
ShowErrorDialog(ex.Message);
}
catch (ObjectDisposedException ex)
{
ShowErrorDialog(ex.Message);
}
}
private void AcceptCallback(IAsyncResult AR)
{
try
{
clientSocket = serverSocket.EndAccept(AR);
buffer = new byte[clientSocket.ReceiveBufferSize];
// Send a message to the newly connected client.
var sendData = Encoding.ASCII.GetBytes("Hello");
clientSocket.BeginSend(sendData, 0, sendData.Length, SocketFlags.None, SendCallback, null); //SendCallback
// Listen for client data.
clientSocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, ReceiveCallback, null);
// Continue listening for clients.
serverSocket.BeginAccept(AcceptCallback, null);
}
catch (SocketException ex)
{
ShowErrorDialog(ex.Message);
}
catch (ObjectDisposedException ex)
{
ShowErrorDialog(ex.Message);
}
}
private void SendCallback(IAsyncResult AR)
{
try
{
clientSocket.EndSend(AR);
}
catch (SocketException ex)
{
ShowErrorDialog(ex.Message);
}
catch (ObjectDisposedException ex)
{
ShowErrorDialog(ex.Message);
}
}
private void ReceiveCallback(IAsyncResult AR)
{
try
{
// Socket exception will raise here when client closes, as this sample does not
// demonstrate graceful disconnects for the sake of simplicity.
int received = clientSocket.EndReceive(AR);
if (received == 0)
{
return;
}
// The received data is deserialized in the PersonPackage ctor.
PersonPackage person = new PersonPackage(buffer);
SubmitPersonToDataGrid(person);
// Start receiving data again.
clientSocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, ReceiveCallback, null);
}
// Avoid Pokemon exception handling in cases like these.
catch (SocketException ex)
{
ShowErrorDialog(ex.Message);
}
catch (ObjectDisposedException ex)
{
ShowErrorDialog(ex.Message);
}
}