I have a windows service written in C# which has opens a TCP socket. I've connected and tested this TCP socket through telnet, and I am able to send and receive messages to the socket through putty with the telnet protocol. When connecting with a small python script, the script is able to receive messages, but unable to send them such that they are received by the C# server. The code for the server is:
IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
TcpListener listener = new TcpListener(ipAddress, 5555);
listener.Start();
Thread whileThread = new Thread(() =>
{
while (true)
{
TcpClient client = listener.AcceptTcpClient();
Thread childThread = new Thread(() =>
{
NetworkStream stream = client.GetStream();
StreamReader streamreader = new StreamReader(client.GetStream(), Encoding.ASCII);
string line = null;
WriteToNetworkStream(stream, "Connected to the service");
eventLog1.WriteEntry("TCP Socket opened");
eventLog1.WriteEntry((GetState(client) == TcpState.Established).ToString()); //this does return True.
while ((line = streamreader.ReadLine()) != "<EOF>" && GetState(client) == TcpState.Established)
{
eventLog1.WriteEntry(line);
}
eventLog1.WriteEntry("TCP Socket closed");
stream.Close();
client.Close();
});
childThread.Start();
}
});
whileThread.Start();
The python script on the other side is:
import socket
import time
TCP_IP = '127.0.0.1'
TCP_PORT = 5555
BUFFER_SIZE = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
time.sleep(1)
s.send("this is a test")
time.sleep(10)
data = s.recv(BUFFER_SIZE)
print(data)
The message "this is a test" is never received by the other side, but "TCP Socket closed" isn't logged until after after the time.sleep(10) is done, showing the C# does recognize some sort of prolonged connection. Also, the data variable does contain "Connected to the service" as expected, showing the server can send data to the client. Like I said earlier, when trying to send and receive messages using telnet with putty, this does work correctly.