Android套接字客户端不发送消息

时间:2014-08-05 18:07:55

标签: java android sockets tcpclient

我在Android上开发套接字客户端。 连接:

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

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

        try {
            InetAddress serverAddr = InetAddress.getByName(ip.getText().toString());
            socket = new Socket(serverAddr, Integer.parseInt(port.getText().toString()));

        } catch (UnknownHostException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return null;
    }

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

按钮:连接到服务器并发送消息(测试):

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    if (v.getId() == R.id.buttonConnect){
        new MyClientTask().execute();
    }
    else if (v.getId() == R.id.buttonTest){
        try {
            PrintWriter out = new PrintWriter(new BufferedWriter(
                    new OutputStreamWriter(socket.getOutputStream())),
                    true);
            out.println("String");
            out.flush();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }   
}

服务器(Java)

public class Server {
    public static void main(String args[]) throws Exception {
        String clientSentence;
        String capitalizedSentence;

        System.out.println(InetAddress.getLocalHost());

        ServerSocket welcomeSocket = new ServerSocket(6000);

        while(true) {
            Socket connectionSocket = welcomeSocket.accept();
            BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
            DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
            clientSentence = inFromClient.readLine();
            capitalizedSentence = clientSentence.toUpperCase() + '\n';
            outToClient.writeBytes(capitalizedSentence);
            System.out.println(clientSentence);
        }
    }
}

只有按下按钮&#34; buttonTest&#34;时才会发送消息第一次。在成功之后没有任何反应。 如何解决?

0 个答案:

没有答案