如何使用Socket编程在两个Android设备之间共享文件?

时间:2015-02-19 12:26:51

标签: android eclipse client-server serversocket

我是Android开发的新手我试图使用套接字编程在两个Android设备之间共享文件

我有代码在服务器和客户端之间发送文本,但我试图将图像或其他文件从客户端设备发送到服务器

我的代码在这里 服务器端代码

public void run() {
OutputStream outputStream;


String msgReply = "Hello from Android, you are #" + cnt;
try {
outputStream = hostThreadSocket.getOutputStream();
         PrintStream printStream = new PrintStream(outputStream);
         printStream.print(msgReply);
         printStream.close();

message += "replayed: " + msgReply + "\n";

MainActivity.this.runOnUiThread(new Runnable() {

 @Override
 public void run() {
  msg.setText(message);
 }
});



}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
message += "Something wrong! " + e.toString() + "\n";


}
MainActivity.this.runOnUiThread(new Runnable() {

@Override
public void run() {
 msg.setText(message);
}


});}

客户端代码

public class MyClientTask extends AsyncTask<Void, Void, Void> {


String dstAddress;


int dstPort;


String response = "";
MyClientTask(String addr, int port){


dstAddress = addr;


  dstPort = port;


 }

@Override


  protected Void doInBackground(Void... arg0) {



Socket socket = null;
try {
socket = new Socket(dstAddress, dstPort);

ByteArrayOutputStream byteArrayOutputStream = 
              new ByteArrayOutputStream(1024);
byte[] buffer = new byte[1024];

int bytesRead;
InputStream inputStream = socket.getInputStream();

/*
 * notice:
 * inputStream.read() will block if no data return
 */
         while ((bytesRead = inputStream.read(buffer)) != -1){
             byteArrayOutputStream.write(buffer, 0, bytesRead);
             response += byteArrayOutputStream.toString("UTF-8");
         }



}
catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "UnknownHostException: " + e.toString();


}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "IOException: " + e.toString();


}
finally{
if(socket != null){
 try {
  socket.close();
 } catch (IOException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 }
}


}
 return null;


}
 @Override


protected void onPostExecute(Void result) {

 textResponse.setText(response);
super.onPostExecute(result);
}
}

由于

0 个答案:

没有答案