从android客户端向pc java服务器发送文件

从android客户端向pc java服务器发送文件,java,android,netbeans,serversocket,Java,Android,Netbeans,Serversocket,代码正常工作,没有任何问题,我只是想让它能够做文件传输,现在我只能够做从服务器到客户端和viceversa的文本聊天 我应该在哪里进行更改以启用文件传输 我是android编程新手,我真的可以利用你宝贵的知识 这是我的主要活动MyActivity.java package com.aghil.adesara.socket.client; 导入java.util.ArrayList import android.annotation.SuppressLint; impor

代码正常工作,没有任何问题,我只是想让它能够做文件传输,现在我只能够做从服务器到客户端和viceversa的文本聊天

我应该在哪里进行更改以启用文件传输

我是android编程新手,我真的可以利用你宝贵的知识

这是我的主要活动MyActivity.java

    package com.aghil.adesara.socket.client;
导入java.util.ArrayList

    import android.annotation.SuppressLint;
    import android.app.Activity;
    import android.content.Intent;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.ListView;

    import com.aghil.custom.adapter.MyCustomAdapter;

    //Display Activity with sending messages to server


    @SuppressLint("NewApi")
    public class MyActivity extends Activity
    {
private ListView mList;
private ArrayList<String> arrayList;
private MyCustomAdapter mAdapter;
private TCPClient mTcpClient = null;
private connectTask conctTask = null;

@Override
public void onCreate(Bundle savedInstanceState)
{

    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    arrayList = new ArrayList<String>();

    final EditText editText = (EditText) findViewById(R.id.editText);
    Button send = (Button)findViewById(R.id.send_button);

    //relate the listView from java to the one created in xml
    mList = (ListView)findViewById(R.id.list);
    mAdapter = new MyCustomAdapter(this, arrayList);
    mList.setAdapter(mAdapter);

    mTcpClient = null;
    // connect to the server
    conctTask = new connectTask();
    conctTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

    send.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String message = editText.getText().toString();
            //add the text in the arrayList
            arrayList.add("Android Client: " + message);
            //sends the message to the server
            if (mTcpClient != null) 
            {
                mTcpClient.sendMessage("Android Client: "+message);
            }
            //refresh the list
            mAdapter.notifyDataSetChanged();
            editText.setText("");
        }
    });
}


 // receive the message from server with asyncTask

public class connectTask extends AsyncTask<String,String,TCPClient> {
    @Override
    protected TCPClient doInBackground(String... message) 
    {
        //we create a TCPClient object and
        mTcpClient = new TCPClient(new TCPClient.OnMessageReceived() 
        {
            @Override
            //here the messageReceived method is implemented
            public void messageReceived(String message)
            {
                try
                {
                    //this method calls the onProgressUpdate
                    publishProgress(message);
                    if(message!=null)
                    {

                        //
                        if(message.contains("settings"))
                        {
                            Intent abc = new Intent(android.provider.Settings.ACTION_SETTINGS);
                            startActivity(abc);
                        }

                        if(message.contains("camera")) {
                            Intent cam = getPackageManager().getLaunchIntentForPackage("com.android.camera");
                            startActivity(cam);
                        }

                        if(message.contains("clock")) {
                            Intent cam = getPackageManager().getLaunchIntentForPackage("com.android.deskclock");
                            startActivity(cam);
                        }
                        //
                        System.out.println("Return Message from Socket::::: >>>>> "+message);
                    }
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        });
        mTcpClient.run();
        if(mTcpClient!=null)
        {
            mTcpClient.sendMessage("Initial Message when connected with Socket Server");
        }
        return null;
    }

    @Override
    protected void onProgressUpdate(String... values) {
        super.onProgressUpdate(values);

        //in the arrayList we add the messaged received from server
        arrayList.add(values[0]);

        // notify the adapter that the data set has changed. This means that new message received
        // from server was added to the list
        mAdapter.notifyDataSetChanged();
    }
}

@Override
protected void onDestroy()
{
    try
    {
        System.out.println("onDestroy.");
        mTcpClient.sendMessage("bye");
        mTcpClient.stopClient();
        conctTask.cancel(true);
        conctTask = null;
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
    super.onDestroy();
}
}

现在我在netbeans IDE中有了我的pc服务器代码 这是我的服务器板

package com.aghilmohammed.server;

    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;

    import javax.swing.BoxLayout;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;

    public class ServerBoard extends JFrame
    {
        private static final long serialVersionUID = 1L;
        private JTextArea messagesArea;
        private JButton sendButton;
        private JTextField message;
        private JButton startServer;
        private Socketserver mServer;

public ServerBoard()
{

    super("ServerBoard");

    JPanel panelFields = new JPanel();
    panelFields.setLayout(new BoxLayout(panelFields, BoxLayout.X_AXIS));

    JPanel panelFields2 = new JPanel();
    panelFields2.setLayout(new BoxLayout(panelFields2, BoxLayout.X_AXIS));

    // here we will have the text messages screen
    messagesArea = new JTextArea();
    messagesArea.setColumns(30);
    messagesArea.setRows(10);
    messagesArea.setEditable(false);

    sendButton = new JButton("Send");
    sendButton.addActionListener(new ActionListener()
    {
        @Override
        public void actionPerformed(ActionEvent e)
        {
            // get the message from the text view
            String messageText = message.getText();
            if(messageText.toString().trim().equals(""))
            {
                message.setText("");
                message.requestFocus();
                return;
            }
            // add message to the message area
            messageText = "Server: " + messageText;
            messagesArea.append("\n"+messageText);
            // send the message to the client
            mServer.sendMessage(messageText);
            // clear text
            message.setText("");
        }
    });

    startServer = new JButton("Start");
    startServer.addActionListener(new ActionListener()
    {
        @Override
        public void actionPerformed(ActionEvent e)
        {
            // disable the start button
            startServer.setEnabled(false);
            messagesArea.append("Server Started, now start Android Client");
            // creates the object OnMessageReceived asked by the DispatcherServer
            // constructor
            mServer = new Socketserver(new Socketserver.OnMessageReceived()
            {
                @Override
                // this method declared in the interface from DispatcherServer
                // class is implemented here
                // this method is actually a callback method, because it
                // will run every time when it will be called from
                // DispatcherServer class (at while)
                public void messageReceived(String message)
                {
                    System.out.println("Msg Recieved");
                    messagesArea.append("\n" + message);
                }
            });
            mServer.start();

        }
    });

    // the box where the user enters the text (EditText is called in
    // Android)
    message = new JTextField();
    message.setSize(200, 20);
    message.setScrollOffset(1);

    // add the buttons and the text fields to the panel
    JScrollPane sp = new JScrollPane(messagesArea);
    panelFields.add(sp);
    panelFields.add(startServer);

    panelFields2.add(message);
    panelFields2.add(sendButton);

    getContentPane().add(panelFields);
    getContentPane().add(panelFields2);

    getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));

    setSize(300, 170);
    setVisible(true);
}
}

这是我的Socketserver.java

package com.aghilmohammed.server;

    import java.awt.Desktop;
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.io.PrintWriter;
    import java.net.ServerSocket;
    import java.net.Socket;

    import javax.swing.JFrame;



        // The class extends the Thread class so we can receive and send messages at the same time
       public class Socketserver extends Thread
        {
            private int SERVERPORT = 0001;
            private ServerSocket serverSocket;
            private Socket client = null;
            private boolean running = false;
            private PrintWriter mOut;
            private OnMessageReceived messageListener;

public static void main(String[] args)
{
    // opens the window where the messages will be received and sent
    ServerBoard frame = new ServerBoard();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLocationRelativeTo(null); // *** center the app *** 
    frame.pack();
    frame.setVisible(true);
}


 // Constructor of the class messageListener listens for the messages

public Socketserver(OnMessageReceived messageListener)
{
    this.messageListener = messageListener;
}


 // Method to send the messages from server to client

//' message' is the message sent by the server

public void sendMessage(String message)
{
    try
    {
        if (mOut != null && !mOut.checkError())
        {
            System.out.println(message);
            // Here you can connect with database or else you can do what you want with static message
            mOut.println(message);

            mOut.flush();
        }
    }
    catch (Exception e)
    {
    }
}


@Override
public void run()
{
    super.run();
    running = true;
    try
    {
        System.out.println("PA: Connecting...");

        // create a server socket. A server socket waits for requests to come in over the network.
        serverSocket = new ServerSocket(SERVERPORT);

        // create client socket... the method accept() listens for a
        // connection to be made to this socket and accepts it.
        try
        {
            client = serverSocket.accept();
            System.out.println("S: Receiving...");
            // sends the message to the client
            mOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())), true);
            System.out.println("PA: Sent");
            System.out.println("PA: Connecting Done.");
            // read the message received from client
            BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));

            sendMessage("Server connected with Android Client now you can chat with socket server.");

            // in this while we wait to receive messages from client (it's an infinite loop)
            // this while it's like a listener for messages
            while (running)
            {
                String message = in.readLine();
                if (message != null && messageListener != null)
                {
                    // call the method messageReceived from ServerBoard class
                    messageListener.messageReceived(message);

                                            //
                                            if(message.contains("notepad"))   
                                            //System.out.println(message);
                                            {
                                                    Runtime runTime = Runtime.getRuntime();
                                             Process process = runTime.exec("notepad");
                                            }

                                            //
                                            if(message.contains("vlc"))   
                                            //System.out.println(message);
                                            {
                                                    try {
                                                          Desktop.getDesktop().open(new File("E:/downloads/Cristiano Ronaldo, Real Madrid's all-time leading goalscorer._Full-HD.mp4"));
                                                             }                                                      
                                                    catch (IOException e) {
                                                             // TODO Auto-generated catch block
                                                             e.printStackTrace();
                                                                            }
                                            }

                                             if(message.contains("skype"))   
                                            //System.out.println(message);
                                            {
                                                    try {
                                                          Process p = Runtime.getRuntime().exec("C:/Program Files (x86)/Skype/Phone/Skype.exe");
                                                             }                                                      
                                                    catch (IOException e) {
                                                             // TODO Auto-generated catch block
                                                             e.printStackTrace();
                                                                            }
                                            }


                                              if(message.contains("chrome"))   
                                            //System.out.println(message);
                                            {
                                                    try {
                                                          Process p = Runtime.getRuntime().exec("C:/Program Files (x86)/Google/Chrome/Application/chrome.exe");
                                                             }                                                      
                                                    catch (IOException e) {
                                                             // TODO Auto-generated catch block
                                                             e.printStackTrace();
                                                                            }
                                            }



                                               if(message.contains("goodbye"))   
                                            //System.out.println(message);
                                            {
                                                    System.exit(0);
                                            }




                }
            }
        }
        catch (Exception e)
        {
            System.out.println("PA: Error: "+e.getMessage());
            e.printStackTrace();
        }
        finally
        {
            client.close();
            System.out.println("PA: Done.");
        }
    }
    catch (Exception e)
    {
        System.out.println("PA: Error");
        e.printStackTrace();
    }

}

// Declare the interface. The method messageReceived(String message) will
// must be implemented in the ServerBoard
//class at on startServer button click

public interface OnMessageReceived
{
    public void messageReceived(String message);
}

}我希望这会对你有所帮助。。您可以将文件作为base64字符串发送,您可以将其作为json数据的普通字符串参数传递

FileOutputStream fout = new FileOutputStream(path + ".txt");
FileInputStream fin = new FileInputStream(path);

System.out.println("File Size:" + path.length());

ByteArrayOutputStream os = new ByteArrayOutputStream();
Base64OutputStream base64out = new Base64OutputStream(os,Base64.NO_WRAP);

byte[] buffer = new byte[3 * 512];
int len = 0;
while ((len = fin.read(buffer)) >= 0) {
  base64out.write(buffer, 0, len);
}

System.out.println("Encoded Size:" + os.size());

base64out.flush();
base64out.close();//this did the tricks. Please see explanation.

String result = new String(os.toByteArray(), "UTF-8");      

 fout.write(os.toByteArray());
 fout.flush();
 fout.close();
 os.close();
 fin.close();

 return result;

尊敬的先生,您能告诉我在我现有的代码中应该在哪里添加此代码吗
FileOutputStream fout = new FileOutputStream(path + ".txt");
FileInputStream fin = new FileInputStream(path);

System.out.println("File Size:" + path.length());

ByteArrayOutputStream os = new ByteArrayOutputStream();
Base64OutputStream base64out = new Base64OutputStream(os,Base64.NO_WRAP);

byte[] buffer = new byte[3 * 512];
int len = 0;
while ((len = fin.read(buffer)) >= 0) {
  base64out.write(buffer, 0, len);
}

System.out.println("Encoded Size:" + os.size());

base64out.flush();
base64out.close();//this did the tricks. Please see explanation.

String result = new String(os.toByteArray(), "UTF-8");      

 fout.write(os.toByteArray());
 fout.flush();
 fout.close();
 os.close();
 fin.close();

 return result;