无法读取从python上的TCP客户端发送到C#中的TCP服务器的数据

问题描述

我有一个用C#编写的Windows服务,该服务打开了一个TCP套接字。我已经通过telnet连接并测试了此TCP套接字,并且能够使用telnet协议通过腻子向套接字发送和接收消息。使用小型python脚本连接时,该脚本能够接收消息,但无法发送消息,以致C#服务器无法接收到它们。服务器的代码是:

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();

另一边的python脚本是:

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)

消息“这是一个测试”从未被对方接收,但是直到time.sleep(10)完成之后才记录“ TCP套接关闭”,这表明C#确实可以识别某种延长连接。此外,数据变量确实包含“连接到服务”,这表明服务器可以将数据发送到客户端。就像我之前说过的,当尝试使用带有腻子的telnet发送和接收消息时,这确实可以正常工作。

解决方法

您是否尝试过从网络流中读取字节?我不能说这是否会有所作为,但是值得一试来检查实际的字节是否输入:

NetworkStream stream = client.GetStream();
Byte[] bytes = new Byte[256]; //whatever size is appropriate
int bytesRead;
string data;
while ((bytesRead = stream.Read(bytes,bytes.Length)) != 0)
{
    data = System.Text.Encoding.ASCII.GetString(bytes,bytesRead);
    // ......
}