我有一个 Python 服务器和一个 Java 客户端。当一个字符串从 java 发送到 python 时,它是不完整的。示例:
Java 代码发送:Hellooooooooo
在 Python 中接收为:
he
lloooooooo
oo
这是代码
Python 服务器:
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ("localhost", 10000)
print 'starting up on %s port %s' % server_address
sock.bind(server_address)
sock.listen(5)
while True:
print 'waiting for a connection'
connection, client_address = sock.accept()
try:
print 'connection from', client_address
while True:
data = connection.recv(1024)
print 'received: ' + data
print type(data)
if data:
print 'sending data back to the client'
connection.sendall(data)
else:
print 'no more data from', client_address
break
finally:
connection.close()
Java 客户端:
package server;
import java.io.*;
import java.net.*;
class Reciever_test {
public static void main(String args[]) throws Exception {
String sentence;
String modifiedSentence;
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
Socket clientSocket = new Socket("localhost", 10000);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
while(true)
{
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + "\n");
modifiedSentence = inFromServer.readLine();
System.out.println("FROM SERVER:" + modifiedSentence);
}
//clientSocket.close();
}
最佳答案
Klaus D. 所说的是徒劳的,recv 保证它最多等待多少数据,它可能决定在达到大小之前处理它拥有的数据。我使用了一个简单的缓冲区,尽管我确信可能有更好的方法:
import socket
import atexit
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ("localhost", 10000)
print ('starting up on %s port %s' % server_address)
sock.bind(server_address)
sock.listen(5)
def close(connection):
connection.close()
while True:
print ('waiting for a connection')
connection, client_address = sock.accept()
atexit.register(close, connection)
try:
print ('connection from', client_address)
buffer=[]
while True:
data = connection.recv(1024)
for b in data:
buffer.append(b)
print ('received: ' + str(data))
print (type(data))
if str(buffer[-1]) == '\n': #if changed to use the buffer to decide when done receiving, the newline is the terminator
print ('sending data back to the client')
connection.sendall(''.join(buffer))
buffer = []
# else:
# print ('no more data from', client_address)
# break
finally:
close(connection)
atexit 是在您的程序崩溃时优雅地关闭套接字
关于java - Python 服务器没有从 Java 客户端接收到完整的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36422665/