Reputation: 371
My Problem is when my client sends data, my server does it only get it the first sent message. All following client messages the server doesn't receive. If I debug the client it does not throw any exception so I think the problem is with the acceptance of the server.
Can someone tell how to fix my code that my client is able to send multiple times to the server without creating a new socket(on the client) for every message?
Server:
static Socket connection;
static IPEndPoint endpoint;
const int BUFFER_SIZE = 1024;
static byte[] buffer;
static void Main(string[] args)
{
connection = new Socket(SocketType.Stream, ProtocolType.Tcp);
endpoint = new IPEndPoint(IPAddress.Any, 1337);
connection.Bind(endpoint);
connection.Listen(10);
buffer = new byte[BUFFER_SIZE];
connection.BeginAccept(new AsyncCallback(AsyncAccept),null);
Console.ReadLine();
}
private static void AsyncAccept(IAsyncResult ar)
{
Socket s = connection.EndAccept(ar);
s.BeginReceive(buffer,0,BUFFER_SIZE, SocketFlags.None, new AsyncCallback(AsyncReceive),s);
connection.BeginAccept(new AsyncCallback(AsyncAccept), null);
}
static void AsyncReceive(IAsyncResult ar)
{
Socket s = (Socket)ar.AsyncState;
int received = s.EndReceive(ar); //END
byte[] data = new byte[received];
Array.Copy(buffer, data, received);
string text = Encoding.Default.GetString(data);
Console.WriteLine(text);
}
Client:
Socket c;
IPEndPoint endpoint;
string text;
public MainWindow()
{
InitializeComponent();
c = new Socket(SocketType.Stream, ProtocolType.Tcp);
endpoint = new IPEndPoint(IPAddress.Loopback, 1337);
c.Connect(endpoint);
}
private void Send()
{
byte[] buffer = Encoding.Default.GetBytes(text);
c.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(SendAsync), c);
}
private void SendAsync(IAsyncResult ar)
{
Socket s = (Socket)ar.AsyncState;
s.EndSend(ar);
}
private void btnSend_Click(object sender, RoutedEventArgs e)
{
Thread t = new Thread(Send);
text = txtMessage.Text;
t.IsBackground = true;
t.Start();
}
Upvotes: 2
Views: 179
Reputation: 63722
You need to start another BeginReceive
in your AsyncReceive
handler. The original asynchronous receive is done - you're only going to get the one response you asked for.
Also, don't think about messages when talking about TCP - it's a stream-based protocol, there's no messages. If you want to send (and receive) messages over TCP, you need to implement your own message protocol on top of TCP.
I'd suggest reading a bit more about how networking (and asynchronous I/O in general) works - just like with multi-threading, it's very easy to get something that mostly works, but is impossible to debug and fix properly. The simplest example being your treating TCP as a message-based protocol - it will tend to mostly work on localhost and in very constrained networking conditions, but it's not safe, and it's going to blow up in your face.
Upvotes: 2