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

2024-06-28 21:57:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个用C#编写的windows服务,它打开了一个TCP套接字。我已经通过telnet连接并测试了这个TCP套接字,我能够通过putty和telnet协议向套接字发送和接收消息。当与一个小型python脚本连接时,该脚本能够接收消息,但无法发送消息以便C#server接收消息。服务器的代码为:

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)

消息“this is a test”(这是一个测试)从未被另一方接收到,但“TCP套接字关闭”直到时间过后才被记录。睡眠(10)完成,表明C#确实识别出某种延长的连接。此外,数据变量确实包含预期的“连接到服务”,表明服务器可以向客户端发送数据。正如我前面所说,当尝试使用带有putty的telnet发送和接收消息时,这确实可以正常工作


Tags: 脚本client消息newstreamlinesocketthis
1条回答
网友
1楼 · 发布于 2024-06-28 21:57:23

您是否尝试过从网络流中读取字节?我不能说这是否会产生影响,但值得一试,看看是否有实际字节进入:

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

相关问题 更多 >