2012-03-14 4 views
0

ソケットプログラミングを使用して、クライアントからサーバーにファイルを送信します。 私はこのファイルを転送することができません、クライアント側はメッセージをOK、サーバはserverClient.acceptでフリーズし、dispalysのみを受け取ります。
Ip:10.81.81.125を聞いて、とても混乱しています。 ありがとうございます。データフォームソケットをAndroidのServerSocketに送信するには?

Client Code: 
    public class uploadData extends AsyncTask<String, String, String> { 
     @Override 
     public void onPreExecute() { 

      } catch (Exception e) { 
      } 

     } 

     @Override 
     protected String doInBackground(String... arg0) { 
       try { 
        InetAddress serverAddr = InetAddress.getByName(serverIpAddress); 
        Log.d("ClientActivity", "C: Connecting..."); 
        Socket socket = new Socket(serverAddr, Constants.SERVERPORT); 
        socket.setSoTimeout(90000); 

        connected = true; 
        if (connected) { 
         try { 
          Log.d("ClientActivity", "C: Sending command."); 
          PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket 
             .getOutputStream())), true); 
          try { 
           // where you issue the commands 
           File sFile = new File(filePath); 
           BufferedInputStream buffIn = null; 
           buffIn = new BufferedInputStream(
             new FileInputStream(sFile)); 
           out.print(buffIn); 
          } catch (Exception e) { 
           // TODO: handle exception 
          } 
//       setText(); 
//        out.println("Hey Server!"); 
           Log.d("ClientActivity", "C: Sent."); 
         } catch (Exception e) { 
          Log.e("ClientActivity", "S: Error", e); 
         } 
        } 
        socket.close();      
        Log.d("ClientActivity", "C: Closed."); 
       } catch (Exception e) { 

        e.printStackTrace(); 
        Toast.makeText(SynServer.this,getString(R.string.noServer), Toast.LENGTH_SHORT).show(); 
        connected = false; 
       } 

      return null; 
     } 

     @Override 
     protected void onProgressUpdate(String... progress) { 
      // TODO Auto-generated method stub 
      super.onProgressUpdate(progress); 

     } 

     @Override 
     protected void onPostExecute(String result) { 
      super.onPostExecute(result); 

     } 
    } 


    @Override 
    protected void onDestroy() { 
     Runtime.getRuntime().gc(); 
     super.onDestroy(); 
    } 
} 

サーバコード:

public class Socket_File_ServerActivity extends Activity { 

      private TextView serverStatus; 

     // default ip 
      public static String SERVERIP = "10.0.2.15"; 

      // designate a port 
      public static final int SERVERPORT =12345; 

      private Handler handler = new Handler(); 

      private ServerSocket serverSocket; 
      Socket client=null; 

      @Override 
     protected void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 
      setContentView(R.layout.main); 
       serverStatus = (TextView) findViewById(R.id.server_status); 

       SERVERIP = getLocalIpAddress(); 
//  
      Thread fst = new Thread(new ServerThread()); 
       fst.start(); 
      } 

     public class ServerThread implements Runnable { 

      public void run() { 
       try { 
        Looper.prepare(); 
        if (SERVERIP != null) { 
         handler.post(new Runnable() { 
          public void run() { 
           serverStatus.setText("Listening on IP: " + SERVERIP); 
          } 
         }); 
         serverSocket = new ServerSocket(SERVERPORT); 
         handler.post(new Runnable() { 
          public void run() { 
           Toast.makeText(getApplicationContext(), serverSocket.getLocalSocketAddress().toString() 
             , Toast.LENGTH_LONG).show(); 
             serverStatus.append("\n"+serverSocket.getLocalSocketAddress().toString()); 

          } 
         }); 



         Toast.makeText(getApplicationContext(), serverSocket.getLocalSocketAddress().toString() 
         , Toast.LENGTH_LONG).show(); 
         serverStatus.append("\n"+serverSocket.getLocalSocketAddress().toString()); 
         while (true) { 
          // listen for incoming clients 
          Socket client = serverSocket.accept(); 
          handler.post(new Runnable() { 
           public void run() { 
            serverStatus.setText("Connected."); 
           } 
          }); 

          try { 
           BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream())); 
           String line = null; 
           while ((line = in.readLine()) != null) { 
            Log.d("ServerActivity", line); 

            final String myline=new String(line); 
            handler.post(new Runnable() { 
             public void run() { 
//           tv_chatbox.setText("Client said:="+myline); 

              // do whatever you want to the front end 
              // this is where you can be creative 
             } 
            }); 
           } 
           break; 
          } catch (Exception e) { 
           handler.post(new Runnable() { 
            public void run() { 
             serverStatus.setText("Oops. Connection interrupted. Please reconnect your phones."); 
            } 
           }); 
           e.printStackTrace(); 
          } 
         } 
        } else { 
         handler.post(new Runnable() { 
          public void run() { 
           serverStatus.setText("Couldn't detect internet connection."); 
          } 
         }); 
        } 
       } catch (final Exception e) { 
        handler.post(new Runnable() { 
         public void run() { 
          serverStatus.setText("Error"+e.getMessage()); 

         } 
        }); 
        e.printStackTrace(); 
       } 
      } 
     } 


     // gets the ip address of your phone's network 
      private String getLocalIpAddress() { 
      try { 
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) { 
         NetworkInterface intf = en.nextElement(); 
         for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) { 
          InetAddress inetAddress = enumIpAddr.nextElement(); 
         if (!inetAddress.isLoopbackAddress()) { return inetAddress.getHostAddress().toString(); } 
         } 
        } 
       } catch (SocketException ex) { 
        Log.e("ServerActivity", ex.toString()); 
      } 
      return null; 
     } 

     @Override 
     protected void onStop() { 
      super.onStop(); 
      try { 
       // make sure you close the socket upon exiting 
       serverSocket.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
      } 


} 

答えて

0

クライアント

public class TCPServer { 
    //tcp port on local host port 
    public static final int PORT = 3100; 

    public static void main(String[] args) throws IOException { 
     ServerSocket serverSocket = null; 
     try { 
      //server socket, can also specify Host Address 
      serverSocket = new ServerSocket(PORT); 
      //start listening on port 
      System.out.println("Listening for clients on port: " + PORT); 
     } catch (IOException e) { 
      System.err.println("Could not listen on port: " + PORT); 
      System.err.println(e.getMessage()); 
      System.exit(-1); 
     } 
     //create new thread pool 
     ThreadPool threadPool = new ThreadPool(2); 
     //call runnable method on thread pool 
     threadPool.runTask(startServer(serverSocket)); 
     //join thread pool 
     threadPool.join(); 

     //close server socket and destroy threadpool 
     serverSocket.close(); 
     threadPool.destroy(); 
    } 

    private static Runnable startServer(final ServerSocket socket) { 
     return new Runnable() { 

      @Override 
      public void run() { 
       //keep looping and looking for data 
       while (true) 
        try { 
         //create new thread 
         new TCPServerThread(socket.accept()).start(); 
        } catch (IOException e) { 
         System.out.println("Client got disconnected!" + "\nListening for clients on port: " + PORT); 
        } 
      } 
     }; 
    } 
} 

サーバー

import java.io.BufferedInputStream; 
import java.io.IOException; 
import java.net.Socket; 

import javazoom.jl.decoder.JavaLayerException; 
import javazoom.jl.player.Player; 

public class TCPServerThread extends Thread { 
    private Socket socket = null; 
    //constructor 
    public TCPServerThread(Socket socket) { 
     this.socket = socket; 
    } 

    public void run() { 

     try { 
      //read data into buffered stream 
      BufferedInputStream stream = new BufferedInputStream(
        socket.getInputStream()); 
      //create music player object with buffered stream 
      Player p = new Player(stream); 
      //start playing 
      p.play(); 
      //close socket after done playing 
      socket.close(); 

     } catch (IOException e) { 
      System.out.println("Client got disconnected!" + "\nListening for clients on port: " + TCPServer.PORT); 
     } catch (JavaLayerException e) { 
      System.out.println("Client got disconnected!" + "\nListening for clients on port: " + TCPServer.PORT); 
     } 
    } 
} 

スレッドプール私の場合は

import java.util.LinkedList; 

class ThreadPool extends ThreadGroup { 

    private boolean isAlive; 

    private LinkedList<Runnable> taskQueue; 

    private int threadID; 

    private static int threadPoolID; 
    //constructor 
    public ThreadPool(int numThreads) { 
     super("ThreadPool-" + (threadPoolID++)); 
//  Changes the daemon status of this thread group. 
     setDaemon(true); 

     isAlive = true; 

     taskQueue = new LinkedList<Runnable>(); 
     for (int i = 0; i < numThreads; i++) { 
      new PooledThread().start(); 
     } 
    } 

    public synchronized void runTask(Runnable task) { 
     if (!isAlive) { 
      throw new IllegalStateException(); 
     } 
     if (task != null) { 
      taskQueue.add(task); 
      notify(); 
     } 

    } 

    protected synchronized Runnable getTask() throws InterruptedException { 
     while (taskQueue.size() == 0) { 
      if (!isAlive) { 
       return null; 
      } 
      wait(); 
     } 
     return (Runnable) taskQueue.removeFirst(); 
    } 

    public synchronized void close() { 
     if (isAlive) { 
      isAlive = false; 
      taskQueue.clear(); 
      interrupt(); 
     } 
    } 

    public void join() { 
     // notify all waiting threads that this ThreadPool is no 
     // longer alive 
     synchronized (this) { 
      isAlive = false; 
      notifyAll(); 
     } 

     // wait for all threads to finish 
     Thread[] threads = new Thread[activeCount()]; 
     int count = enumerate(threads); 
     for (int i = 0; i < count; i++) { 
      try { 
       threads[i].join(); 
      } catch (InterruptedException ex) { 
      } 
     } 
    } 

    private class PooledThread extends Thread { 

     public PooledThread() { 
      super(ThreadPool.this, "PooledThread-" + (threadID++)); 
     } 

     public void run() { 
      while (!isInterrupted()) { 

       // get a task to run 
       Runnable task = null; 
       try { 
        task = getTask(); 
       } catch (InterruptedException ex) { 
       } 

       // if getTask() returned null or was interrupted, 
       // close this thread by returning. 
       if (task == null) { 
        return; 
       } 

       // run the task, and eat any exceptions it throws 
       try { 
        task.run(); 
       } catch (Throwable t) { 
        uncaughtException(this, t); 
       } 
      } 
     } 
    } 
} 
+0

私は音楽がサーバにオーバーファイルを送信しようとしていますが、それは、Android – Mayank

+0

ソケットクライアント= serverSocket.acceptのために実施することができる任意のデータ型と同じコードすることができます() ; get freezes ....... :( –

+0

あなたのネットワーク上で何らかの問題がありますが、私はこのコードを使ってバックアップを取っています。 – Mayank

関連する問題