尝试通过Java服务器和python客户端发送文件。
from socket import socket
def main():
s = socket()
s.connect(("localhost", 6030))
while True:
f = open("archivo.txt", "rb")
content = f.read(1024)
while content:
#Enviar contenido
s.send(content + '\n')
content = f.read(1024)
break
# Se utiliza el caracter de código 1 para indicar
# al cliente que ya se ha enviado todo el contenido.
try:
s.send(chr(1))
except TypeError:
# Compatibilidad con Python 3.
s.send(bytes(chr(1), "utf-8"))
# Cerrar conexión y archivo.
s.close()
f.close()
print("El archivo ha sido enviado correctamente.")
if __name__ == "__main__":
main()
import java.net.*;
import java.io.*;
public class Server {
public static void main (String []args) {
try {
ServerSocket ss = new ServerSocket(6030);
Socket s = ss.accept();
DataInputStream dis = new DataInputStream(s.getInputStream());
String k = dis.readUTF();
System.out.println("File Transferred");
FileOutputStream fos = new FileOutputStream("D:\\yo.txt");
byte[] b = k.getBytes();
fos.write(k.getBytes());
} catch (IOException ie) {
ie.printStackTrace();
}
}
}
出现此错误
java.io.EOFException
at java.io.DataInputStream.readFully(Unknown Source)
at java.io.DataInputStream.readUTF(Unknown Source)
at java.io.DataInputStream.readUTF(Unknown Source)
at Server.main(Server.java:10)
感谢任何帮助。我有python服务器和java客户端,它工作得很好。此外,它们在python客户端服务器和java客户端服务器之间也能很好地工作]
readUTF的一般约定是,它读取以经修改的UTF-8格式编码的Unicode字符串的表示形式。
您应该使用以byte数组作为参数的read方法。这是一个例子
try {
ServerSocket ss = new ServerSocket(6030);
Socket s = ss.accept();
DataInputStream dis = new DataInputStream(s.getInputStream());
byte[] buffer = new byte[dis.available()];
dis.readFully(buffer, 0, buffer.length);
FileOutputStream fos = new FileOutputStream("c:\\Users\\username\\Desktop\\yo.txt");
fos.write(buffer);
fos.flush();
fos.close();
} catch (IOException ie) {
ie.printStackTrace();
}