简体   繁体   中英

Unable to send message from server to the client in android through text field

UPDATE: ok so I kept trying to press send until I received the java.net.SocketException: sendto failed: EPIPE (Broken pipe) exception as a toast message once and then there was no activity once again when I pressed the send button. Meaning I didn't get the exception again.

I have two apps where one acts as the server and the other as a client. I was able to send a message from the server to the client like this

dataOutputStream.writeUTF("hello");

basically as a hardcoded string

but when I added a textfield and a button to the server app and tried listening to the onClick like this

sendChatbtn.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {

                    try {
                        dataOutputStream.writeUTF(chatMsg);
                    } catch (IOException e) {
                        e.printStackTrace();
                        Toast.makeText(ServerActivity.this, "An exception occurred: " + e.toString(), Toast.LENGTH_SHORT).show();
                        // TODO Auto-generated catch block

                    }

                }

                });

Absolutely NOTHING happened when I press the SEND button and the client did not receive any message, I don't even get any exception as a toast. By the way I am able to send messages from the client to the server and the server receives the client's messages but the client doesn't get any messages from the server.

The logcat although shows this:

08-09 04:13:45.694: E/LocSvc_adapter(761): E/virtual loc_api_adapter_err LocApiV02Adapter::injectPosition(double, double, float):632]: error! status = eLOC_CLIENT_FAILURE_INVALID_PARAMETER, inject_pos_ind.status = UNKNOWN

08-09 04:15:25.220: A/ActivityManager(761): Service ServiceRecord{42e78d58 u0 com.estrongs.android.pop/com.estrongs.android.ui.notification.ESTaskService} in process ProcessRecord{449c4320 9734:com.estrongs.android.pop/u0a245} not same as in map: null

08-09 04:16:06.444: E/AudioStreamOutALSA(269): PCM_Write set_amp_mode,1

Here's my Server code:

public class ServerActivity extends Activity {

TextView info, infoip, msg;
String message = "";
ServerSocket serverSocket;
EditText chatBoxText;
Button sendChatbtn, startGameBtn;

Socket socket = null;
DataInputStream dataInputStream = null;
DataOutputStream dataOutputStream = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_server_socket);
    info = (TextView) findViewById(R.id.info);
    infoip = (TextView) findViewById(R.id.infoip);
    msg = (TextView) findViewById(R.id.msg);
    chatBoxText=(EditText) findViewById(R.id.chatBox);
    sendChatbtn=(Button) findViewById(R.id.sendChatButton);
    startGameBtn=(Button) findViewById(R.id.startGamebutton);
    infoip.setText(getIpAddress());

    Thread socketServerThread = new Thread(new SocketServerThread());
    socketServerThread.start();
}

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

    if (serverSocket != null) {
        try {
            serverSocket.close();
            closeSockets();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Toast.makeText(ServerActivity.this, "An exception occurred: " + e.toString(), Toast.LENGTH_SHORT).show();
        }
    }
}

private class SocketServerThread extends Thread {

    static final int SocketServerPORT = 8080;
    int count = 0;

    String chatMsg = chatBoxText.getText().toString();
    @Override
    public void run() {


        try {
            serverSocket = new ServerSocket(SocketServerPORT);
            ServerActivity.this.runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    info.setText("I'm waiting here: "
                            + serverSocket.getLocalPort());
                }
            });

            while (true) {
                socket = serverSocket.accept();
                dataInputStream = new DataInputStream(
                        socket.getInputStream());
                dataOutputStream = new DataOutputStream(
                        socket.getOutputStream());

                String messageFromClient = "";

                //If no message sent from client, this code will block the program
                messageFromClient = dataInputStream.readUTF();

                count++;
                message += "#" + count + " from " + socket.getInetAddress()
                        + ":" + socket.getPort() + "\n"
                        + "Msg from client: " + messageFromClient + "\n";

                ServerActivity.this.runOnUiThread(new Runnable() {

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

                    }
                });

                sendChatbtn.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {

                    try {
                        dataOutputStream.writeUTF(chatMsg);
                    } catch (IOException e) {
                        e.printStackTrace();
                        Toast.makeText(ServerActivity.this, "An exception occurred: " + e.toString(), Toast.LENGTH_SHORT).show();
                        // TODO Auto-generated catch block

                    }

                }

                });

            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Toast.makeText(ServerActivity.this, "An exception occurred: " + e.toString(), Toast.LENGTH_SHORT).show();
            final String errMsg = e.toString();
            ServerActivity.this.runOnUiThread(new Runnable() {

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

        }           

    }




}

private 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 += "SiteLocalAddress: "
                            + inetAddress.getHostAddress() + "\n";
                }

            }

        }

    } catch (SocketException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        ip += "Something Wrong! " + e.toString() + "\n";
        Toast.makeText(ServerActivity.this, "An exception occurred: " + e.toString(), Toast.LENGTH_SHORT).show();
    }

    return ip;
}

public void closeSockets()
{
            try {
                socket.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                Toast.makeText(ServerActivity.this, "An exception occurred: " + e.toString(), Toast.LENGTH_SHORT).show();
            }
            try {
                dataInputStream.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                Toast.makeText(ServerActivity.this, "An exception occurred: " + e.toString(), Toast.LENGTH_SHORT).show();
            }
            try {
                dataOutputStream.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                Toast.makeText(ServerActivity.this, "An exception occurred: " + e.toString(), Toast.LENGTH_SHORT).show();
            }
}

}

Here's the Client Code:

public class ClientActivity extends Activity {

TextView textResponse;
EditText editTextAddress, editTextPort;
Button buttonConnect, buttonClear;

EditText welcomeMsg;
private MyClientTask myClientTask;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_client);
    editTextAddress = (EditText) findViewById(R.id.address);
    editTextPort = (EditText) findViewById(R.id.port);
    buttonConnect = (Button) findViewById(R.id.connect);
    buttonClear = (Button) findViewById(R.id.clear);
    textResponse = (TextView) findViewById(R.id.response);

    welcomeMsg = (EditText)findViewById(R.id.welcomemsg);

    buttonConnect.setOnClickListener(buttonConnectOnClickListener);

    buttonClear.setOnClickListener(new OnClickListener() {

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

OnClickListener buttonConnectOnClickListener = new OnClickListener() {

    @Override
    public void onClick(View arg0) {

        String tMsg = welcomeMsg.getText().toString();
        if(tMsg.equals("")){
            tMsg = null;
            Toast.makeText(ClientActivity.this, "No Welcome Msg sent", Toast.LENGTH_SHORT).show();
        }

        MyClientTask myClientTask = new MyClientTask(editTextAddress
                .getText().toString(), Integer.parseInt(editTextPort
                .getText().toString()),
                tMsg);
        myClientTask.execute();
    }
};


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

    String dstAddress;
    int dstPort;
    String response = "";
    String msgToServer;
    Socket socket = null;
    DataOutputStream dataOutputStream = null;
    DataInputStream dataInputStream = null;

    MyClientTask(String addr, int port, String msgTo) {
        dstAddress = addr;
        dstPort = port;
        msgToServer = msgTo;
    }

    @Override
    protected Void doInBackground(Void... arg0) {



        try {
            socket = new Socket(dstAddress, dstPort);
            dataOutputStream = new DataOutputStream(
                    socket.getOutputStream());
            dataInputStream = new DataInputStream(socket.getInputStream());

            if(msgToServer != null){
                dataOutputStream.writeUTF(msgToServer);
            }

            response = dataInputStream.readUTF();

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

    protected void CloseSockets()
    {

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



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


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

    }
    @Override
    protected void onPostExecute(Void result) {
        textResponse.setText(response);
        super.onPostExecute(result);
    }


}

protected void onDestroy()
{
    myClientTask.CloseSockets();
    super.onDestroy();
}

}

You are not updating the chatMsg string after the onClick, so it initializes as a zero length string, and does not change.

When onClick occurs, you need to get the current string from your TextView:

            @Override
            public void onClick(View v) {
                // add this!!!

                chatMsg = chatBoxText.getText().toString();


                try {
                    dataOutputStream.writeUTF(chatMsg);
                } catch (IOException e) {
                    e.printStackTrace();
                    Toast.makeText(ServerActivity.this, "An exception occurred: " + e.toString(), Toast.LENGTH_SHORT).show();
                    // TODO Auto-generated catch block

                }

            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM