我在从Java客户端向python服务器发送TCP消息时遇到一些奇怪的行为,特别是在使用write(byte[] b)
和writeBytes(String s)
时存在差异。
我正在使用找到here的python服务器,缓冲区大小设置为1024(发送的消息很少超过100个字节,永远不会超过200个):
#!/usr/bin/env python
# encoding: utf-8
#
# Copyright (c) 2010 Doug Hellmann. All rights reserved.
#
"""Server half of echo example.
"""
#end_pymotw_header
import socket
import sys
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to the port
server_address = ('localhost', 39277)
print >>sys.stderr, 'starting up on %s port %s' % server_address
sock.bind(server_address)
# Listen for incoming connections
sock.listen(1)
while True:
# Wait for a connection
print >>sys.stderr, 'waiting for a connection'
connection, client_address = sock.accept()
try:
print >>sys.stderr, 'connection from', client_address
# Receive the data in small chunks and retransmit it
while True:
data = connection.recv(1024)
#print >>sys.stderr, 'received "%s"' % data
if data:
print >>sys.stderr, 'received "%s"' % data
else:
print >>sys.stderr, 'no more data from', client_address
break
finally:
# Clean up the connection
connection.close()
当我使用writeBytes(msg)
时,python服务器会分割消息:
starting up on localhost port 39277
waiting for a connection
connection from ('127.0.0.1', 53948)
received "$PNG"
received "VEST,LOCATION,1,144291"
received "1960"
received "50"
received "7,"
....
但是当我将字符串转换为字节数组时:
byte[] b = msg.getBytes();
DataOutputStream.write(b);
它没有拆分消息,并按预期收到消息:
connection from ('127.0.0.1', 53956)
received "$PNGVEST,LOCATION,1,1442912048641,,,,,,0"
received "$PNGVEST,LOCATION,1,1442912049655,51.55866171044861,-3.0430628338367187,0.0,1.25,148.87440204525353,0"
received "$PNGVEST,LOCATION,1,1442912050656,51.5586532525196,-3.043054619198384,0.0,1.25,148.87440290497682,0"
为什么会这样?