java中如何实现TCP服务器和TCP客户端传输文件 [英] how to implement TCP server and TCP client in java to transfer files

查看:29
本文介绍了java中如何实现TCP服务器和TCP客户端传输文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经实现了简单的 TCP 服务器和 TCP 客户端类,它们可以将消息从客户端发送到服务器,并且消息将在服务器端转换为大写,但是如何实现从服务器到客户端的文件传输和上传从客户端到服务器的文件.以下代码是我得到的.

I have implement the simple TCP server and TCP client classes which can send the message from client to server and the message will be converted to upper case on the server side, but how can I achieve transfer files from server to client and upload files from client to server. the following codes are what I have got.

TCPClient.java:

import java.io.*;
import java.net.*;

class TCPClient {
 public static void main(String args[]) throws Exception {
        String sentence;
        String modifiedSentence;
        BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
        Socket clientSocket = new Socket("127.0.0.1", 6789);
        DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
        BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        sentence = inFromUser.readLine();
        outToServer.writeBytes(sentence + "
");
        modifiedSentence = inFromServer.readLine();
        System.out.println("FROM SERVER:" + modifiedSentence);
        clientSocket.close();
    }
}

TCPServer.java:

import java.io.*;
import java.net.*;

class TCPServer {
    public static void main(String args[]) throws Exception {
        int firsttime = 1;
        while (true) {
            String clientSentence;
            String capitalizedSentence="";
            ServerSocket welcomeSocket = new ServerSocket(3248);
            Socket connectionSocket = welcomeSocket.accept();
            BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
            DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
            clientSentence = inFromClient.readLine();
            //System.out.println(clientSentence);
            if (clientSentence.equals("set")) {
                outToClient.writeBytes("connection is ");
                System.out.println("running here");
                //welcomeSocket.close();
                //outToClient.writeBytes(capitalizedSentence);
            }
            capitalizedSentence = clientSentence.toUpperCase() + "
";
            //if(!clientSentence.equals("quit"))
            outToClient.writeBytes(capitalizedSentence+"enter the message or command: ");
            System.out.println("passed");
            //outToClient.writeBytes("enter the message or command: ");
            welcomeSocket.close();
            System.out.println("connection terminated");
        }
    }
}

所以,会先执行TCPServer.java,然后再执行TCPClient.java,我尝试使用TCPServer中的if子句.java 来测试用户的输入是什么,现在我真的很想实现如何从双方传输文件(下载和上传).谢谢.

So, the TCPServer.java will be executed first, and then execute the TCPClient.java, and I try to use the if clause in the TCPServer.java to test what is user's input,now I really want to implement how to transfer files from both side(download and upload).Thanks.

推荐答案

所以让我们假设在服务器端你已经收到了文件名和文件路径.这段代码应该会给你一些想法.

So lets assume on server side you have received the file name and file path. This code should give you some idea.

服务器

PrintStream out = new PrintStream(socket.getOutputStream(), true);
FileInputStream requestedfile = new FileInputStream(completeFilePath);
byte[] buffer = new byte[1];
out.println("Content-Length: "+new File(completeFilePath).length()); // for the client to receive file
while((requestedfile.read(buffer)!=-1)){
    out.write(buffer);
    out.flush();    
    out.close();    
}
requestedfile.close();

客户

DataInputStream in = new DataInputStream(socket.getInputStream());
int size = Integer.parseInt(in.readLine().split(": ")[1]);
byte[] item = new byte[size];
for(int i = 0; i < size; i++)
    item[i] = in.readByte();
FileOutputStream requestedfile = new FileOutputStream(new File(fileName));
BufferedOutputStream bos = new BufferedOutputStream(requestedfile);
bos.write(item);
bos.close();
fos.close();

这篇关于java中如何实现TCP服务器和TCP客户端传输文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆