Android Studio客户端 - 服务器消息挣扎

时间:2016-10-11 19:41:04

标签: android server client message

我在android studio和客户端应用程序中有一个服务器应用程序。

虽然客户端能够连接到服务器,但我似乎无法将消息传递给客户端。我对网络概念很陌生,所以我会非常感激你的帮助。

我的主要活动类:

public class MainActivity extends Activity {

    Server server;
    TextView infoip, msg;
    TextView usersTitle;
    EditText userInput;
    Button sendButton;
    String[] array = {""};
    public static ArrayList<String> lst;
    ArrayAdapter<String> adapter;
    ListView userList;
    OutputStream outputStream;
    int receivedPort;
    InetAddress receivedIP;




    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        infoip = (TextView) findViewById(R.id.infoip);
        msg = (TextView) findViewById(R.id.msg);
        userInput = (EditText) findViewById(R.id.userInput);
        sendButton = (Button) findViewById(R.id.sendButton);
        usersTitle = (TextView) findViewById(R.id.usersTitle);
        server = new Server(this);
        infoip.setText(server.getIpAddress() + ":" + server.getPort());

        userList = (ListView) findViewById(R.id.userList);
        lst = new ArrayList<String>(Arrays.asList(array));
        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, lst);
        userList.setAdapter(adapter);



        userList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                                                String selected = userList.getItemAtPosition(position).toString();
                                                msg.append("\n" + selected + " Client Port: " + receivedPort + " Client IP: " + receivedIP );


                                            }
                                        }
        );



        sendButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                final String input = userInput.getText().toString();

                Socket socket = null;

                try {
                    socket = new Socket("192.168.1.11",receivedPort);
                    outputStream = new ObjectOutputStream(socket.getOutputStream());
                    outputStream.write(input.getBytes());
                    msg.append(socket.getOutputStream().toString());
                } catch (IOException e) {
                    e.printStackTrace();
                }


            }
        });


    }

    public int getClientPort(int port){
        receivedPort = port;
        return receivedPort;

    }

    public InetAddress getClientIP(InetAddress ip){
        receivedIP = ip;
        return receivedIP;

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        server.onDestroy();
    }

    }

我的服务器类:

public class Server {
    MainActivity activity;
    ServerSocket serverSocket;
    String message = "";
    static final int socketServerPORT = 8080;

    public Server(MainActivity activity) {
        this.activity = activity;
        Thread socketServerThread = new Thread(new SocketServerThread());
        socketServerThread.start();
    }

    public int getPort() {
        return socketServerPORT;
    }

    public void onDestroy() {
        if (serverSocket != null) {
            try {
                serverSocket.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    private class SocketServerThread extends Thread {

        int count = 0;

        @Override
        public void run() {
            try {
                // create ServerSocket using specified port
                serverSocket = new ServerSocket(socketServerPORT);

                while (true) {
                    // block the call until connection is created and return
                    // Socket object
                    final Socket socket = serverSocket.accept();
                    count++;
                    message += " #" + count + " from " + socket.getInetAddress() + ":" + socket.getPort() + "\n"
                            + " Host Name: " + socket.getInetAddress().getHostName() + "\n";
                    final String host = socket.getInetAddress().getHostName();

                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {

                            activity.msg.setText(message);
                            activity.lst.add(host);
                            activity.adapter.notifyDataSetChanged();
                            activity.usersTitle.setText("Connected Users (" + count + ")");
                            activity.getClientIP(socket.getInetAddress());
                            activity.getClientPort(socket.getPort());

                        }
                    });

                    SocketServerReplyThread socketServerReplyThread =
                            new SocketServerReplyThread(socket, count);
                    socketServerReplyThread.run();

                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    private class SocketServerReplyThread extends Thread {

        private Socket hostThreadSocket;
        int cnt;

        SocketServerReplyThread(Socket socket, int c) {
            hostThreadSocket = socket;
            cnt = c;
        }

        @Override
        public void run() {
            OutputStream outputStream;
            String msgReply = " Hello from Server, you are #" + cnt;

            try {
                outputStream = hostThreadSocket.getOutputStream();
                PrintStream printStream = new PrintStream(outputStream);
                printStream.print(msgReply);
                printStream.close();

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

                activity.runOnUiThread(new Runnable() {

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

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

            activity.runOnUiThread(new Runnable() {

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

    }

    public String getIpAddress() {
        String ip = "";
        try {
            Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface
                    .getNetworkInterfaces();
            while (enumNetworkInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = enumNetworkInterfaces
                        .nextElement();
                Enumeration<InetAddress> enumInetAddress = networkInterface
                        .getInetAddresses();
                while (enumInetAddress.hasMoreElements()) {
                    InetAddress inetAddress = enumInetAddress
                            .nextElement();

                    if (inetAddress.isSiteLocalAddress()) {
                        ip += " Server running at : " + inetAddress.getHostAddress();
                    }
                }
            }

        } catch (SocketException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            ip += " Something Wrong! " + e.toString() + "\n";
        }
        return ip;
    }
}

我的客户主要活动:

    public class MainActivity extends Activity {

        TextView response;
        EditText editTextAddress, editTextPort;
        Button buttonConnect, buttonClear, callClass;
        Intent intent;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            editTextAddress = (EditText) findViewById(R.id.addressEditText);
            editTextPort = (EditText) findViewById(R.id.portEditText);
            response = (TextView) findViewById(R.id.responseTextView);
            buttonConnect = (Button) findViewById(R.id.connectButton);
            buttonClear = (Button) findViewById(R.id.clearButton);
            callClass = (Button) findViewById(R.id.callClass);



            callClass.setOnClickListener(
                new Button.OnClickListener() {
                    public void onClick (View v){

                        intent = new Intent(MainActivity.this, ClientInterface.class);
                        startActivity(intent);
                        finish();
                }
            } );



            buttonConnect.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    Client myClient = new Client("192.168.1.13", 8080, response);
                    myClient.execute();
                }
            });

            buttonClear.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    response.setText("");
                }
            });
        }

    }

My Client class:

    package com.example.seth.chat4all_client;



import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import android.os.AsyncTask;
import android.widget.TextView;

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

    String dstAddress;
    int dstPort;
    String response = "";
    TextView textResponse;

    Client(String addr, int port, TextView textResponse) {
        dstAddress = addr;
        dstPort = port;
        this.textResponse = textResponse;
    }

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

}

当消息发送到客户端时,我收到以下错误消息:

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.example.seth.chat4all, PID: 9296
              android.os.NetworkOnMainThreadException
                  at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
                  at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:110)
                  at libcore.io.IoBridge.connectErrno(IoBridge.java:137)
                  at libcore.io.IoBridge.connect(IoBridge.java:122)
                  at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:183)
                  at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:163)
                  at java.net.Socket.startupSocket(Socket.java:590)
                  at java.net.Socket.tryAllAddresses(Socket.java:128)
                  at java.net.Socket.<init>(Socket.java:178)
                  at java.net.Socket.<init>(Socket.java:150)
                  at com.example.seth.chat4all.MainActivity$2.onClick(MainActivity.java:83)
                  at android.view.View.performClick(View.java:4789)
                  at android.view.View$PerformClick.run(View.java:19881)
                  at android.os.Handler.handleCallback(Handler.java:739)
                  at android.os.Handler.dispatchMessage(Handler.java:95)
                  at android.os.Looper.loop(Looper.java:135)
                  at android.app.ActivityThread.main(ActivityThread.java:5294)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at java.lang.reflect.Method.invoke(Method.java:372)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)

1 个答案:

答案 0 :(得分:-1)

您正在尝试在主线程上进行网络连接,这将阻止任何UI操作, 请参阅How to fix android.os.NetworkOnMainThreadException?了解此

的解决方案