无法通过文本字段将消息从服​​务器发送到android中的客户端

时间:2014-08-09 03:40:15

标签: java android sockets tcp client-server

更新:好的所以我一直试图按发送直到我收到java.net.SocketException:sendto failed:EPIPE(Broken pipe)异常作为Toa​​st消息一次然后当我再次没有活动时按下发送按钮。意思是我没有再次获得例外。

我有两个应用程序,其中一个充当服务器,另一个充当客户端。我能够像这样从服务器向客户端发送消息

dataOutputStream.writeUTF("hello");

基本上是一个硬编码的字符串

但是当我向服务器应用添加了一个文本字段和一个按钮并试图像这样听取onClick

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

                    }

                }

                });

当我按下SEND按钮并且客户端没有收到任何消息时,绝对没有发生任何消息,我甚至没有得到任何例外的吐司。顺便说一下,我能够从客户端向服务器发送消息,服务器接收客户端的消息,但客户端没有从服务器收到任何消息。

logcat虽然显示了这个:

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

这是我的服务器代码:

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

}

这是客户代码:

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

}

1 个答案:

答案 0 :(得分:0)

您没有在onClick之后更新chatMsg字符串,因此它初始化为零长度字符串,并且不会更改。

当发生onClick时,您需要从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

                }

            }