Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/341.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python到C#TCP传输会破坏超过1523字节的数据_C#_Python_Sockets_Tcp - Fatal编程技术网

Python到C#TCP传输会破坏超过1523字节的数据

Python到C#TCP传输会破坏超过1523字节的数据,c#,python,sockets,tcp,C#,Python,Sockets,Tcp,我试图从python服务器向C#客户端发送一个长字符串。字符串的长度为230400字节。我正在发送和接收64字节的数据块。服务器代码: import socket def initialize(): global s s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(('', 1719)) s

我试图从python服务器向C#客户端发送一个长字符串。字符串的长度为230400字节。我正在发送和接收64字节的数据块。服务器代码:

import socket

def initialize():
  global s
  s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  s.bind(('', 1719))
  s.listen()

initialize()

while(1):
  sock, addr = s.accept()

  msgstr = generate_msg_string() # irrelevant

  msglen = len(msgstr)

  totalsent = 0
  while totalsent < msglen:
    sent = sock.send(msgstr[totalsent:totalsent+64])
    totalsent = totasent + sent

  sock.close()
我已经连续检查了几个连接——前1523个字节是正确的,其余的都是胡言乱语——至少看起来是随机的


知道原因是什么吗?

看来我提这个问题很匆忙

将TcpClient更改为套接字修复了该问题。方法保持不变

while(i != 230400)
{
    stream.Read(buffer, 0, 64);
    buffer.CopyTo(ba, i);
    i += 64;
}
这里的基本错误是假定
读取
读取64字节。它可以读取以下任何内容:

  • 如果套接字因任何原因关闭,则为0
  • 64字节,如果它选择
  • 1-63字节,只是为了好玩
除了“如果流已关闭,则为非正,否则至少为1字节且不超过64字节”之外,您不保证任何其他内容

必须读取
read
的返回值,并且只处理那么多的缓冲区。顺便说一句,如果您切换到
插座,情况仍然是这样

还有-为什么不首先填充
ba
,增加偏移量并每次减少计数

int count = 230400, offset = 0, read;
byte[] ba = new byte[count];
while(count > 0 && (read=stream.Read(ba, offset, count)) > 0)
{
    offset += read;
    count -= read;
}
if(read!=0) throw new EndOfStreamException();

@MarcGravel是正确的-通过不忽略read()返回的结果来修复它。这确实有帮助。我收到的字符串现在完全正确。非常感谢。
int count = 230400, offset = 0, read;
byte[] ba = new byte[count];
while(count > 0 && (read=stream.Read(ba, offset, count)) > 0)
{
    offset += read;
    count -= read;
}
if(read!=0) throw new EndOfStreamException();