2015-11-01 137 views
-1

代碼正常工作沒有任何問題我只是想讓它能夠做文件傳輸,現在我只是能夠做文本聊天從服務器到客戶端反之亦然。發送文件從Android客戶端到PC JAVA服務器

我應該在哪裏進行更改以啓用文件傳輸?

我是新來的Android編程和我真的可以用你的知識,居停

這是我mainactivity 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(); 
} 

}

這是我的TCPclient.java文件

package com.aghil.adesara.socket.client; 

    import java.io.BufferedReader; 
    import java.io.BufferedWriter; 
    import java.io.InputStreamReader; 
    import java.io.OutputStreamWriter; 
    import java.io.PrintWriter; 
    import java.net.InetAddress; 
    import java.net.Socket; 
    import android.util.Log; 

     public class TCPClient { 

private String serverMessage; 

// Specify the Server Ip Address here. 

public static final String SERVERIP = "192.168.173.1"; // your computer IP address 
public static final int SERVERPORT = 0001; 
private OnMessageReceived mMessageListener = null; 
private boolean mRun = false; 

private PrintWriter out = null; 
private BufferedReader in = null; 

// Constructor of the class. OnMessagedReceived listens for the messages received from server 

public TCPClient(final OnMessageReceived listener) 
{ 
    mMessageListener = listener; 
} 

//Sends the message entered by client to the server 

public void sendMessage(String message){ 
    if (out != null && !out.checkError()) { 
     System.out.println("message: "+ message); 
     out.println(message); 
     out.flush(); 
    } 
} 

public void stopClient(){ 
    mRun = false; 
} 

public void run() { 

    mRun = true; 

    try { 
     //here you must put your computer's IP address. 
     InetAddress serverAddr = InetAddress.getByName(SERVERIP); 

     Log.e("TCP SI Client", "SI: Connecting..."); 

     //create a socket to make the connection with the server 
     Socket socket = new Socket(serverAddr, SERVERPORT); 
     try { 

      //send the message to the server 
      out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true); 

      Log.e("TCP SI Client", "SI: Sent."); 

      Log.e("TCP SI Client", "SI: Done."); 

      //receive the message which the server sends back 
      in = new BufferedReader(new InputStreamReader(socket.getInputStream())); 

      //in this while the client listens for the messages sent by the server 
      while (mRun) { 
       serverMessage = in.readLine(); 

       if (serverMessage != null && mMessageListener != null) { 
        //call the method messageReceived from MyActivity class 
        mMessageListener.messageReceived(serverMessage); 
        Log.e("RESPONSE FROM SERVER", "S: Received Message: '" + serverMessage + "'"); 
       } 
       serverMessage = null; 
      } 
     } 
     catch (Exception e) 
     { 
      Log.e("TCP SI Error", "SI: Error", e); 
      e.printStackTrace(); 
     } 
     finally 
     { 
      //the socket must be closed. It is not possible to reconnect to this socket 
      // after it is closed, which means a new socket instance has to be created. 
      socket.close(); 
     } 

    } catch (Exception e) { 

     Log.e("TCP SI Error", "SI: Error", e); 

    } 

} 

//Declare the interface. The method messageReceived(String message) will must be implemented in the MyActivity 
//class at on asynckTask doInBackground 
public interface OnMessageReceived { 
    public void messageReceived(String message); 
} 

}

現在我已經在NetBeans IDE 我的電腦服務器代碼,這是我的服務器board.java

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); 
} 

}

回答

0

我希望這將幫助你..你可以發送文件爲base64字符串,您可以通過正常的字符串PARAM您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; 
+0

尊敬的先生,你能告訴我在哪裏應該添加此代碼在我現有的代碼 –

相關問題