如何在Android中将数据从Socket发送到ServerSocket?

时间:2012-03-14 10:25:51

标签: android

我想使用套接字编程将文件从客户端发送到服务器。 我无法传输此文件,客户端正在给出消息OK,服务器在serverClient.accept上冻结,并且只显示聆听  是的:10.81.81.125,我很困惑,请帮助。 提前谢谢。

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


}

1 个答案:

答案 0 :(得分: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);
                }
            }
        }
    }
}