I have this code. I can receive data from my client successfully, but only one time. After I receive the data once, if the client attempts to send any more the server isn’t receiving it. Can anyone help?
private void startListening()
{
TcpListener server = null;
try
{
server = new TcpListener(IPAddress.Parse("127.0.0.1"), 7079);
server.Start();
Byte[] bytes = new Byte[256];
String data = null;
//Enter listening loop
while (true)
{
addLog("Waiting for push.");
TcpClient client = server.AcceptTcpClient();
addLog("Push request received, accepted.");
data = null;
NetworkStream stream = client.GetStream();
int i;
//Loop to receive all data
while((i = stream.Read(bytes, 0, bytes.Length))!=0)
{
//Translate data bytes to ASCII string
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
//Process data
data = data.ToUpper();
byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
//send response
stream.Write(msg, 0, msg.Length);
addLog("Received: '" + data + "'");
}
//End ALL Connections
client.Close();
server.Stop();
}
}
catch(SocketException e)
{
addLog("SocketException: " + e);
}
finally
{
//Stop listening for new clients
MessageBox.Show("Finished.");
}
}
You are closing both the server and the client in the end of your loop (
server.Stop();). Your outer loop will keep going and try to get a new TcpClient from your server (which would mean a new connection is made) but since you’ve already stopped the server then that will never happen (or probably throw an exception).