如何使用java socket实现客户端和服务器之间的文件传输 [英] how to achieve transfer file between client and server using java socket

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

问题描述

我已经实现了简单的 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

TCPClient.java

        import java.io.*;
        import java.net.*;
        import java.util.Scanner;

 class TCPClient {

public static void main(String args[]) throws Exception {
        int filesize=6022386;
        int bytesRead;
        int current = 0;
    String ipAdd="";
    int portNum=0;
    boolean goes=false;
    if(goes==false){
    System.out.println("please input the ip address of the file server");
    Scanner scan=new Scanner(System.in);
    ipAdd=scan.nextLine();
    System.out.println("please input the port number of the file server");
    Scanner scan1=new Scanner(System.in);
    portNum=scan1.nextInt();
    goes=true;
    }
    System.out.println("input done");
    int timeCount=1;
    while(goes==true){
    //System.out.println("connection establishing");

    String sentence="";
    String modifiedSentence;

    BufferedReader inFromUser = new BufferedReader(new InputStreamReader(
            System.in));

    Socket clientSocket = new Socket(ipAdd, portNum);
    //System.out.println("connecting");
    //System.out.println(timeCount);
    if(timeCount==1){
    sentence="set";
    //System.out.println(sentence);


    }
    if(timeCount!=1)
        sentence = inFromUser.readLine();
            if(sentence.equals("close"))
                clientSocket.close();
            if(sentence.equals("download"))
            {
                byte [] mybytearray  = new byte [filesize];
                InputStream is = clientSocket.getInputStream();
                FileOutputStream fos = new FileOutputStream("C:\users\cguo\kk.lsp");
                BufferedOutputStream bos = new BufferedOutputStream(fos);
                bytesRead = is.read(mybytearray,0,mybytearray.length);
                current = bytesRead;
                do {
   bytesRead =
      is.read(mybytearray, current, (mybytearray.length-current));
   if(bytesRead >= 0) current += bytesRead;
} while(bytesRead > -1);

bos.write(mybytearray, 0 , current);
bos.flush();
long end = System.currentTimeMillis();
//System.out.println(end-start);
bos.close();
clientSocket.close();
            }
           // if(sentence.equals("send"))
               // clientSocket.
    timeCount--;
    //System.out.println("connecting1");
    DataOutputStream outToServer = new DataOutputStream(clientSocket
            .getOutputStream());

    BufferedReader inFromServer = new BufferedReader(new InputStreamReader(
            clientSocket.getInputStream()));


    //System.out.println("connecting2");
    //System.out.println(sentence);
    outToServer.writeBytes(sentence + "
");

    modifiedSentence = inFromServer.readLine();

    System.out.println("FROM SERVER:" + modifiedSentence);

    clientSocket.close();

}
}

}

TCPServer.java

TCPServer.java

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

     class TCPServer {
public static void main(String args[]) throws Exception {

    Socket s = null;

    int firsttime=1;


    while (true) {
        String clientSentence;
    String capitalizedSentence="";

        ServerSocket welcomeSocket = new ServerSocket(3248);
        Socket connectionSocket = welcomeSocket.accept();

             //Socket sock = 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("download"))
                    {
                         File myFile = new File ("C:\Users\cguo\11.lsp");
  byte [] mybytearray  = new byte [(int)myFile.length()];
  FileInputStream fis = new FileInputStream(myFile);
  BufferedInputStream bis = new BufferedInputStream(fis);
  bis.read(mybytearray,0,mybytearray.length);
  OutputStream os = connectionSocket.getOutputStream();
  System.out.println("Sending...");
  os.write(mybytearray,0,mybytearray.length);
  os.flush();
  connectionSocket.close();
                    }
        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.java中的if子句来测试用户的输入是什么,现在我很想实现如何从双方传输文件(下载和上传).谢谢.

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.

推荐答案

快速阅读源代码,似乎离你不远了.以下链接应该会有所帮助(我做了类似的事情,但用于 FTP).对于从服务器发送到客户端的文件,您从一个文件实例和一个字节数组开始.然后将 File 读入字节数组并将字节数组写入与客户端的 InputStream 对应的 OutputStream.

Reading quickly through the source it seems that you're not far off. The following link should help (I did something similar but for FTP). For a file send from server to client, you start off with a file instance and an array of bytes. You then read the File into the byte array and write the byte array to the OutputStream which corresponds with the InputStream on the client's side.

http://www.rgagnon.com/javadetails/java-0542.html

这是一个工作的超简约文件发送器和接收器.确保您了解代码在双方的作用.

Here's a working ultra-minimalistic file sender and receiver. Make sure you understand what the code is doing on both sides.

package filesendtest;

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

class TCPServer {

    private final static String fileToSend = "C:\test1.pdf";

    public static void main(String args[]) {

        while (true) {
            ServerSocket welcomeSocket = null;
            Socket connectionSocket = null;
            BufferedOutputStream outToClient = null;

            try {
                welcomeSocket = new ServerSocket(3248);
                connectionSocket = welcomeSocket.accept();
                outToClient = new BufferedOutputStream(connectionSocket.getOutputStream());
            } catch (IOException ex) {
                // Do exception handling
            }

            if (outToClient != null) {
                File myFile = new File( fileToSend );
                byte[] mybytearray = new byte[(int) myFile.length()];

                FileInputStream fis = null;

                try {
                    fis = new FileInputStream(myFile);
                } catch (FileNotFoundException ex) {
                    // Do exception handling
                }
                BufferedInputStream bis = new BufferedInputStream(fis);

                try {
                    bis.read(mybytearray, 0, mybytearray.length);
                    outToClient.write(mybytearray, 0, mybytearray.length);
                    outToClient.flush();
                    outToClient.close();
                    connectionSocket.close();

                    // File sent, exit the main method
                    return;
                } catch (IOException ex) {
                    // Do exception handling
                }
            }
        }
    }
}

<小时>

package filesendtest;

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

class TCPClient {

    private final static String serverIP = "127.0.0.1";
    private final static int serverPort = 3248;
    private final static String fileOutput = "C:\testout.pdf";

    public static void main(String args[]) {
        byte[] aByte = new byte[1];
        int bytesRead;

        Socket clientSocket = null;
        InputStream is = null;

        try {
            clientSocket = new Socket( serverIP , serverPort );
            is = clientSocket.getInputStream();
        } catch (IOException ex) {
            // Do exception handling
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        if (is != null) {

            FileOutputStream fos = null;
            BufferedOutputStream bos = null;
            try {
                fos = new FileOutputStream( fileOutput );
                bos = new BufferedOutputStream(fos);
                bytesRead = is.read(aByte, 0, aByte.length);

                do {
                        baos.write(aByte);
                        bytesRead = is.read(aByte);
                } while (bytesRead != -1);

                bos.write(baos.toByteArray());
                bos.flush();
                bos.close();
                clientSocket.close();
            } catch (IOException ex) {
                // Do exception handling
            }
        }
    }
}

相关

java中未知长度的字节数组

以下可用于在传输前后对小文件进行指纹识别(如果您觉得有必要,请使用 SHA):

The following could be used to fingerprint small files before and after transfer (use SHA if you feel it's necessary):

public static String md5String(File file) {
    try {
        InputStream fin = new FileInputStream(file);
        java.security.MessageDigest md5er = MessageDigest.getInstance("MD5");
        byte[] buffer = new byte[1024];
        int read;
        do {
            read = fin.read(buffer);
            if (read > 0) {
                md5er.update(buffer, 0, read);
            }
        } while (read != -1);
        fin.close();
        byte[] digest = md5er.digest();
        if (digest == null) {
            return null;
        }
        String strDigest = "0x";
        for (int i = 0; i < digest.length; i++) {
            strDigest += Integer.toString((digest[i] & 0xff)
                    + 0x100, 16).substring(1).toUpperCase();
        }
        return strDigest;
    } catch (Exception e) {
        return null;
    }
}

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

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