python发送文件到服务器_将文件从Python服务器发送到Java客户端

I am trying to send files from a Python server to Java client over a TCP socket. Here is what I have so far:

Java Client (Note that all of the file transfer code is in the getFile() method):

public class Client1

{

private Socket socket = null;

private FileOutputStream fos = null;

private DataInputStream din = null;

private PrintStream pout = null;

private Scanner scan = null;

public Client1(InetAddress address, int port) throws IOException

{

System.out.println("Initializing Client");

socket = new Socket(address, port);

scan = new Scanner(System.in);

din = new DataInputStream(socket.getInputStream());

pout = new PrintStream(socket.getOutputStream());

}

public void send(String msg) throws IOException

{

pout.print(msg);

pout.flush();

}

public void closeConnections() throws IOException

{

// Clean up when a connection is ended

socket.close();

din.close();

pout.close();

scan.close();

}

// Request a specific file from the server

public void getFile(String filename)

{

System.out.println("Requested File: "+filename);

try {

File file = new File(filename);

// Create new file if it does not exist

// Then request the file from server

if(!file.exists()){

file.createNewFile();

System.out.println("Created New File: "+filename);

}

fos = new FileOutputStream(file);

send(filename);

// Get content in bytes and write to a file

int counter;

byte[] buffer = new byte[8192];

while((counter = din.read(buffer, 0, buffer.length)) != -1)

{

fos.write(buffer, 0, counter);

} }

fos.flush();

fos.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

And the Python Server:

import socket

host = '127.0.0.1'

port = 5555

# Create a socket with port and host bindings

def setupServer():

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

print("Socket created")

try:

s.bind((host, port))

except socket.error as msg:

print(msg)

return s

# Establish connection with a client

def setupConnection():

s.listen(1) # Allows one connection at a time

print("Waiting for client")

conn, addr = s.accept()

return conn

# Send file over the network

def sendFile(filename, s):

f = open(filename, 'rb')

line = f.read(1024)

print("Beginning File Transfer")

while line:

s.send(line)

line = f.read(1024)

f.close()

print("Transfer Complete")

# Loop that sends & receives data

def dataTransfer(conn, s, mode):

while True:

# Send a File over the network

filename = conn.recv(1024)

filename = filename.decode(encoding='utf-8')

filename.strip()

print("Requested File: ", filename)

sendFile(filename, s)

break

conn.close()

s = setupServer()

while True:

try:

conn = setupConnection()

dataTransfer(conn, s, "FILE")

except:

break

I was able to successfully create a messaging program between the server and the client where they passed strings to one another. However, I have been unable to transfer files over the network.

It seems that the Python server is sending over the bytes properly, so the Java side seems to be the problem. Particularly the while loop: while((counter = din.read(buffer, 0, buffer.length)) != -1) has been giving an output of -1 so the writing of the file never actually takes place.

Thanks in advance for the help!

解决方案

For others reference, this is how I got it working in the end.

Server:

import socket

import select

server_addr = '127.0.0.1', 5555

# Create a socket with port and host bindings

def setupServer():

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

print("Socket created")

try:

s.bind(server_addr)

except socket.error as msg:

print(msg)

return s

# Establish connection with a client

def setupConnection(s):

s.listen(5) # Allows five connections at a time

print("Waiting for client")

conn, addr = s.accept()

return conn

# Get input from user

def GET():

reply = input("Reply: ")

return reply

def sendFile(filename, conn):

f = open(filename, 'rb')

line = f.read(1024)

print("Beginning File Transfer")

while line:

conn.send(line)

line = f.read(1024)

f.close()

print("Transfer Complete")

# Loop that sends & receives data

def dataTransfer(conn, s, mode):

while True:

# Send a File over the network

if mode == "SEND":

filename = conn.recv(1024)

filename = filename.decode(encoding='utf-8')

filename.strip()

print("Requested File: ", filename)

sendFile(filename, conn)

# conn.send(bytes("DONE", 'utf-8'))

break

# Chat between client and server

elif mode == "CHAT":

# Receive Data

print("Connected with: ", conn)

data = conn.recv(1024)

data = data.decode(encoding='utf-8')

data.strip()

print("Client: " + data)

command = str(data)

if command == "QUIT":

print("Server disconnecting")

s.close()

break

# Send reply

reply = GET()

conn.send(bytes(reply, 'utf-8'))

conn.close()

sock = setupServer()

while True:

try:

connection = setupConnection(sock)

dataTransfer(connection, sock, "CHAT")

except:

break

Client:

import java.net.*;

import java.io.*;

import java.util.Scanner;

public class ClientConnect {

private Socket socket = null;

private FileOutputStream fos = null;

private DataInputStream din = null;

private PrintStream pout = null;

private Scanner scan = null;

public ClientConnect(InetAddress address, int port) throws IOException

{

System.out.println("Initializing Client");

socket = new Socket(address, port);

scan = new Scanner(System.in);

din = new DataInputStream(socket.getInputStream());

pout = new PrintStream(socket.getOutputStream());

}

public void send(String msg) throws IOException

{

pout.print(msg);

pout.flush();

}

public String recv() throws IOException

{

byte[] bytes = new byte[1024];

din.read(bytes);

String reply = new String(bytes, "UTF-8");

System.out.println("Inside recv(): ");

return reply;

}

public void closeConnections() throws IOException

{

// Clean up when a connection is ended

socket.close();

din.close();

pout.close();

scan.close();

}

public void chat() throws IOException

{

String response = "s";

System.out.println("Initiating Chat Sequence");

while(!response.equals("QUIT")){

System.out.print("Client: ");

String message = scan.nextLine();

send(message);

if(message.equals("QUIT"))

break;

response = recv();

System.out.println("Server: " + response);

}

closeConnections();

}

// Request a specific file from the server

public void getFile(String filename)

{

System.out.println("Requested File: "+filename);

try {

File file = new File(filename);

// Create new file if it does not exist

// Then request the file from server

if(!file.exists()){

file.createNewFile();

System.out.println("Created New File: "+filename);

}

fos = new FileOutputStream(file);

send(filename);

// Get content in bytes and write to a file

byte[] buffer = new byte[8192];

for(int counter=0; (counter = din.read(buffer, 0, buffer.length)) >= 0;)

{

fos.write(buffer, 0, counter);

}

fos.flush();

fos.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以为您提供Java的实现示例。实现TCP文件上传功能的基本步骤与上面Python的实现类似,具体步骤如下: 1. 建立TCP连接。客户服务器之间需要建立TCP连接,可以使用Socket类创建一个socket对象,然后使用connect方法将其连接到指定的服务器地址和口号。 2. 打开文件并读取数据。客户需要打开要上传的文件并读取其中的数据,可以使用Java的FileInputStream类打开文件,然后使用read方法读取文件内容。 3. 发送数据。客户文件数据通过TCP连接发送服务器,可以使用OutputStream类的write方法发送数据。 4. 接收确认消息。服务器接收到数据后,需要发送一个确认消息给客户,表示已经成功接收到数据。客户可以使用InputStream类的read方法接收确认消息。 5. 关闭连接。文件数据发送完成后,客户服务器都需要关闭TCP连接,可以使用close方法关闭连接。 下面是一个简单的Java示例代码,实现了TCP文件上传功能: 客户代码: ```java import java.io.*; import java.net.*; public class TCPFileClient { public static void main(String[] args) { // 设置服务器地址和口号 String host = "127.0.0.1"; int port = 8888; try ( // 建立TCP连接并发送数据 Socket socket = new Socket(host, port); FileInputStream fileIn = new FileInputStream("test.txt"); OutputStream out = socket.getOutputStream(); InputStream in = socket.getInputStream(); ) { byte[] buffer = new byte[1024]; int len; // 读取文件数据并发送 while ((len = fileIn.read(buffer)) > 0) { out.write(buffer, 0, len); } // 接收确认消息 byte[] recvBuffer = new byte[1024]; len = in.read(recvBuffer); String recvMsg = new String(recvBuffer, 0, len); System.out.println(recvMsg); } catch (IOException e) { e.printStackTrace(); } } } ``` 服务器代码: ```java import java.io.*; import java.net.*; public class TCPFileServer { public static void main(String[] args) { // 设置服务器地址和口号 String host = "127.0.0.1"; int port = 8888; try ( // 建立TCP连接并接收数据 ServerSocket serverSocket = new ServerSocket(port); Socket socket = serverSocket.accept(); InputStream in = socket.getInputStream(); OutputStream out = socket.getOutputStream(); ) { byte[] buffer = new byte[1024]; int len; // 接收文件数据 while ((len = in.read(buffer)) > 0) { // 处理文件数据 // ... } // 发送确认消息 out.write("Success".getBytes()); } catch (IOException e) { e.printStackTrace(); } } } ``` 以上代码仅供参考,实际应用中需要根据具体需求进行修改和完善。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值