Good day,
I have a serious problem and need to get it done. Almost spend two days of frustration...
I have a Tcp-Server just waiting for incoming connections and forwarding the received data.
Everything works fine for the first time I receive data, but right after finishing the method my thread closes down - I have no clue why this happens.
Could you have a look at my code and tell me if there is anything wrong?
Code:
private byte[] fByteBuffer = new byte[fConstants.cBUFFERSIZE];
private Socket fServer;
public void Start(){
try {
fServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint vEndPoint = new IPEndPoint(IPAddress.Any, ServerPort);
fServer.Bind(vEndPoint);
fServer.Listen(5);
fServer.BeginAccept(new AsyncCallback(AcceptConnection), fServer);
} catch ( Exception e ) {
throw new Exception("TCVServer.Start() could not create Server", e);
}
}
private void AcceptConnection(IAsyncResult aResult) {
Socket vServer = (Socket)aResult.AsyncState;
Socket vClient = vServer.EndAccept(aResult);
Log("Connection: " + vClient.RemoteEndPoint.ToString());
vClient.BeginReceive(fByteBuffer, 0, fByteBuffer.Length, SocketFlags.None,
new AsyncCallback(ReceiveConnection), vClient);
}
private void ReceiveConnection(IAsyncResult aResult) {
Socket vClient = (Socket)aResult.AsyncState;
int vReceivedBytes = vClient.EndReceive(aResult);
if ( vReceivedBytes > 0 ) {
//These 3 lines handle the received data
TXPacket vPacket = new TXPacket();
vPacket.ReadFromBuffer(fByteBuffer);
fOwner.RemoteAccess(vPacket);
vClient.BeginReceive(fByteBuffer, 0, fByteBuffer.Length, SocketFlags.None,
new AsyncCallback(ReceiveConnection), vClient);
} else {
fServer.BeginAccept(new AsyncCallback(AcceptConnection), fServer);
Log("Connection lost");
}
}