如何发送数据的形式插口至ServerSocket的Andr​​oid中? [英] How to Send Data form Socket to ServerSocket in Android?

查看:174
本文介绍了如何发送数据的形式插口至ServerSocket的Andr​​oid中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用Socket编程从客户发送文件到服务器。
我无法传输文件,客户端在serverClient.accept给消息确定,服务器获取冻结,只有dispalys上侦听结果
 IP:10.81.81.125,我很困惑,请帮助。
先谢谢了。

 客户端code:
    公共类uploadData扩展的AsyncTask<字符串,字符串,字符串> {
        @覆盖
        在preExecute公共无效(){            }赶上(例外五){
            }        }        @覆盖
        保护字符串doInBackground(字符串...为arg0){
               尝试{
                    InetAddress类serverAddr = InetAddress.getByName(serverIpAddress);
                    Log.d(ClientActivity,C:连接...);
                    Socket套接字=新的Socket(serverAddr,Constants.SERVERPORT);
                    Socket的(90000);                    连接= TRUE;
                    如果(连接){
                        尝试{
                            Log.d(ClientActivity,C:发送命令。);
                            为PrintWriter了=的新PrintWriter(新的BufferedWriter(新OutputStreamWriter(插座
                                        .getOutputStream())),TRUE);
                            尝试{
                                 //在这里你发出的命令
                                文件sFile =新的文件(文件路径);
                                的BufferedInputStream buffIn = NULL;
                                buffIn =新的BufferedInputStream(
                                        新的FileInputStream(sFile));
                                的out.print(buffIn);
                            }赶上(例外五){
                                // TODO:处理异常
                            }
//的setText();
//通过out.println(嘿服务器!);
                                Log.d(ClientActivity,C:发送。);
                        }赶上(例外五){
                            Log.e(ClientActivity,S:错误,E);
                        }
                    }
                    socket.close();
                    Log.d(ClientActivity,C:关闭。);
                }赶上(例外五){                    e.printStackTrace();
                    Toast.makeText(SynServer.this,的getString(R.string.noServer),Toast.LENGTH_SHORT).show();
                    连接= FALSE;
                }            返回null;
        }        @覆盖
        保护无效onProgressUpdate(字符串...进度){
            // TODO自动生成方法存根
            super.onProgressUpdate(进度);        }        @覆盖
        保护无效onPostExecute(字符串结果){
            super.onPostExecute(结果);        }
    }
    @覆盖
    保护无效的onDestroy(){
        调用Runtime.getRuntime()GC()。
        super.onDestroy();
    }
}

服务器code:

 公共类Socket_File_ServerActivity延伸活动{            私人TextView的serverStatus;      //默认IP
            公共静态字符串SERVERIP =10.0.2.15;            //指定端口
            公共静态最终诠释SERVERPORT = 12345;            私人处理程序处理程序=新的处理程序();            私人的ServerSocket ServerSocket的;
            客户端的Socket = NULL;            @覆盖
        保护无效的onCreate(捆绑savedInstanceState){
            super.onCreate(savedInstanceState);
            的setContentView(R.layout.main);
                serverStatus =(的TextView)findViewById(R.id.server_status);                SERVERIP = getLocalIpAddress();
//
            螺纹FST =新主题(新ServerThread());
                fst.start();
            }        公共类ServerThread实现Runnable {            公共无效的run(){
                尝试{
                    尺蠖prepare()。
                    如果(SERVERIP!= NULL){
                        handler.post(新的Runnable(){
                            公共无效的run(){
                                serverStatus.setText(听上IP:+ SERVERIP);
                            }
                        });
                        ServerSocket的=新的ServerSocket(SERVERPORT);
                        handler.post(新的Runnable(){
                            公共无效的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());
                        而(真){
                            //监听传入客户
                            客户端的Socket的ServerSocket.accept =();
                            handler.post(新的Runnable(){
                                公共无效的run(){
                                    serverStatus.setText(已连接);
                                }
                             });                            尝试{
                                在的BufferedReader =新的BufferedReader(新的InputStreamReader(client.getInputStream()));
                                串线= NULL;
                                而((行= in.readLine())!= NULL){
                                    Log.d(ServerActivity线);                                  最后弦乐MYLINE =新的String(线);
                                    handler.post(新的Runnable(){
                                        公共无效的run(){
// tv_chatbox.setText(客户说:=+ MYLINE);                                            //做任何你想做的前端
                                            //这是在那里你可以有创意
                                        }
                                    });
                                }
                                打破;
                            }赶上(例外五){
                                handler.post(新的Runnable(){
                                    公共无效的run(){
                                        serverStatus.setText(哎呀连接中断,请重新连接您的电话。);
                                    }
                                });
                                e.printStackTrace();
                            }
                        }
                    }其他{
                        handler.post(新的Runnable(){
                            公共无效的run(){
                                serverStatus.setText(无法​​检测到的网络连接。);
                            }
                        });
                    }
                }赶上(最终例外五){
                    handler.post(新的Runnable(){
                        公共无效的run(){
                            serverStatus.setText(错误+ e.getMessage());                        }
                    });
                    e.printStackTrace();
                }
            }
        }
        //获取手机的网络IP地址
            私人字符串getLocalIpAddress(){
            尝试{
                    对于(枚举<&NetworkInterface的GT; EN = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();){
                        NetworkInterface的INTF = en.nextElement();
                        为(枚举&所述;为InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements()){
                            InetAddress类InetAddress类= enumIpAddr.nextElement();
                        如果(inetAddress.isLoopbackAddress()!){返回inetAddress.getHostAddress()的toString()。 }
                        }
                    }
                }赶上(SocketException前){
                    Log.e(ServerActivity,ex.toString());
            }
            返回null;
        }        @覆盖
        保护无效的onStop(){
            super.onStop();
            尝试{
                 //确保您在退出关闭套接字
                 serverSocket.close();
             }赶上(IOException异常五){
                 e.printStackTrace();
             }
            }
}


解决方案

客户端

 公共类TCPSERVER {
    //本地主机端口的TCP端口
    公共静态最终诠释PORT = 3100;    公共静态无效的主要(字串[] args)抛出IOException
        ServerSocket的ServerSocket的= NULL;
        尝试{
            //服务器插槽,也可以指定主机地址
            ServerSocket的=新的ServerSocket(PORT);
            //启动侦听端口
            的System.out.println(监听端口客户端:+ PORT);
        }赶上(IOException异常五){
            通信System.err.println(无法监听端口:+ PORT);
            通信System.err.println(e.getMessage());
            System.exit(-1);
        }
        //创建新的线程池
        线程池的线程池=新的线程池(2);
        //调用的线程池可运行的方法
        threadPool.runTask(startserver的(ServerSocket的));
        //加入线程池
        threadPool.join();        //关闭服务器套接字和销毁线程池
        serverSocket.close();
        threadPool.destroy();
    }    私有静态可运行startserver的(最终ServerSocket的插座){
        返回新的Runnable(){            @覆盖
            公共无效的run(){
                //继续循环,寻找数据
                而(真)
                    尝试{
                        //创建新的线程
                        新TCPServerThread(socket.accept())开始()。
                    }赶上(IOException异常五){
                        的System.out.println(客户端断开了!+\\ nListening在端口客户端:+ PORT);
                    }
            }
        };
    }
}

服务器

 进口java.io.BufferedInputStream中;
进口java.io.IOException异常;
进口的java.net.Socket;进口javazoom.jl.de coder.JavaLayerException;
进口javazoom.jl.player.Player;公共类TCPServerThread继承Thread {
    私人Socket套接字= NULL;
    //构造
    公共TCPServerThread(Socket套接字){
        this.socket =插座;
    }    公共无效的run(){        尝试{
            //将数据读入缓冲流
            的BufferedInputStream流=新的BufferedInputStream(
                    socket.getInputStream());
            //创建音乐播放器对象,缓冲流
            玩家P =新播放器(流);
            //开始播放
            p.play();
            //关闭套接字完成后打
            socket.close();        }赶上(IOException异常五){
            的System.out.println(客户端断开了!+\\ nListening在端口客户端:+ TCPServer.PORT);
        }赶上(JavaLayerException E){
            的System.out.println(客户端断开了!+\\ nListening在端口客户端:+ TCPServer.PORT);
        }
    }
}

线程池

 进口java.util.LinkedList中;一流的线程池线程组扩展{    私人布尔的isAlive;    私人的LinkedList<&的Runnable GT; TASKQUEUE;    私人诠释主题ID;    私有静态诠释threadPoolID;
    //构造
    公共线程池(INT numThreads){
        超级(ThreadPool-+(threadPoolID ++));
//改变该线程组的后台程序状态。
        setDaemon(真);        的isAlive = TRUE;        TASKQUEUE =新的LinkedList<&的Runnable GT;();
        的for(int i = 0; I< numThreads;我++){
            新PooledThread()开始();
        }
    }    公共同步无效runTask(Runnable任务){
        如果(!的isAlive){
            抛出新IllegalStateException异常();
        }
        如果(任务!= NULL){
            taskQueue.add(任务);
            通知();
        }    }    保护同步的Runnable getTask()抛出InterruptedException的{
        而(taskQueue.size()== 0){
            如果(!的isAlive){
                返回null;
            }
            等待();
        }
        回报(Runnable接口)taskQueue.removeFirst();
    }    公共同步无效的close(){
        如果(的isAlive){
            的isAlive = FALSE;
            taskQueue.clear();
            打断();
        }
    }    公共无效连接(){
        //通知所有等待的线程,该线程池无
        //已经死了
        同步(本){
            的isAlive = FALSE;
            notifyAll的();
        }        //等待所有线程完成
        螺纹[]线程=新主题[活动核心()];
        诠释计数=枚举(线程);
        的for(int i = 0; I<计数;我++){
            尝试{
                线程[I]。加入();
            }赶上(InterruptedException的前){
            }
        }
    }    私有类PooledThread继承Thread {        公共PooledThread(){
            超(ThreadPool.thisPooledThread-+(++的threadId));
        }        公共无效的run(){
            而(!isInterrupted()){                //得到一个任务运行
                Runnable任务= ​​NULL;
                尝试{
                    任务= getTask();
                }赶上(InterruptedException的前){
                }                //如果getTask()返回null或中断,
                //通过返回关闭这个线程。
                如果(任务== NULL){
                    返回;
                }                //运行任务,吃它抛出任何异常
                尝试{
                    task.run();
                }赶上(的Throwable t)的{
                    uncaughtException(这一点,T);
                }
            }
        }
    }
}

I want to send a file from client to Server by using Socket Programming. I unable to transfer this file, client side is giving message OK, server get freeze at serverClient.accept,and only dispalys Listening on
Ip: 10.81.81.125, I am so confused, Kindly help. Thanks in advance.

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

Server Code:

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


}

解决方案

Client

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

Server

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

Thread Pool

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

这篇关于如何发送数据的形式插口至ServerSocket的Andr​​oid中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆