I'm creating a project in which I have to use Socket class to send asynchronous messages in c#.
I've created the project with a client connecting to a server and the client sending messages to server, but now i want the server to respond another byte[] to client with the same socket, but I don't find how to do it, and I performed some tests but it is not working.
As example, now I hace something like that (I reduced it to the base just for you to understand where I am):
Client:
namespace Client
{
public partial class Client : Form
{
private Socket _clientSocket;
private byte[] _buffer;
public Client()
{
InitializeComponent();
}
public void btnConnect_Click(object sender, EventArgs e)
{
_clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_clientSocket.BeginConnect(new IPEndPoint(IPAddress.Loopback, 3333), new AsyncCallback(ConnectCallback), null);
}
private void ConnectCallback(IAsyncResult AR)
{
_clientSocket.EndConnect(AR);
}
private void btnSend_Click(object sender, EventArgs e)
{
string xmlstring = "test";
byte[] xmlbuffer = Encoding.ASCII.GetBytes(xmlstring);
_clientSocket.BeginSend(xmlbuffer, 0, xmlbuffer.Length, SocketFlags.None, new AsyncCallback(SendCallback), null);
}
private void SendCallback(IAsyncResult AR)
{
_clientSocket.EndSend(AR);
_buffer = new byte[_clientSocket.ReceiveBufferSize];
}
}
}
Server:
namespace Server
{
public partial class Server : Form
{
private Socket _serversocket, _clientSocket;
private byte[] _buffer;
public Server()
{
InitializeComponent();
StartServer();
}
private void StartServer()
{
_serversocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_serversocket.Bind(new IPEndPoint(IPAddress.Any, 3333));
_serversocket.Listen(0);
_serversocket.BeginAccept(new AsyncCallback(AcceptCallback), null);
}
private void AcceptCallback(IAsyncResult AR)
{
_clientSocket = _serversocket.EndAccept(AR);
_buffer = new byte[_clientSocket.ReceiveBufferSize];
_clientSocket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), null);
_serversocket.BeginAccept(new AsyncCallback(AcceptCallback), null);
}
private void ReceiveCallback(IAsyncResult AR)
{
int received = _clientSocket.EndReceive(AR);
Array.Resize(ref _buffer, received);
string text = Encoding.ASCII.GetString(_buffer);
Array.Resize(ref _buffer, _clientSocket.ReceiveBufferSize);
}
}
}
I tried to send an answer the other way arround but it did not work, so I would like to ask you how to do it.
Thanks, and sorry if the post is not right, as it is my first one.
asyncandawaitoperators... they allow you to avoid the nastiness ofBegin.../End...APM pairs. This style of API makes it difficult to easily state your intent and leaves program state diffused over several methods. I strongly encourage you to investigate how to rewrite this code usingasyncandawait. It makes life so much easier. stackoverflow.com/questions/12630827/…