0

我在 android 中有一个套接字程序,我想通过单击客户端上的按钮来发送命令或文本消息。并根据按下的按钮发送不同的短信。但我从 PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket .getOutputStream())), true) 收到关于“out” PrintWriter 对象的编译器错误消息;

如果我在 onclick 监听器中使用这个“out”,我该如何修复这个编译器错误?我真的不想把它作为编译器推荐的最终变量作为修复。

这是下面显示的代码,run() 方法中有两个 onclick 按钮侦听器,用于通过套接字从客户端向服务器 android 应用程序发送按摩

如果您点击 sendA 按钮,它会发送短信“testA”,如果您点击 sendB 按钮,它会发送短信“testB”

 public void run() {
        try {
            InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
            Log.d("ClientActivity", "C: Connecting...");
            Socket socket = new Socket(serverAddr, 8080);
            connected = true;
            while (connected) {
                try {
                    Log.d("ClientActivity", "C: Sending command.");
                    PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket
                                .getOutputStream())), true);



                    sendA.setOnClickListener(new View.OnClickListener() {


                    public void onClick(View v) {

                        out.println("testA");

                    }
                });

                    sendB.setOnClickListener(new View.OnClickListener() {


                        public void onClick(View v) {

                            out.println("testB");  

                        }
                    });

                    // where you issue the commands
                       // out.println("testX");


                        Log.d("ClientActivity", "C: Sent.");
                } catch (Exception e) {
                    Log.e("ClientActivity", "S: Error", e);
                }
            }
            socket.close();
            Log.d("ClientActivity", "C: Closed.");
        } catch (Exception e) {
            Log.e("ClientActivity", "C: Error", e);
            connected = false;
        }
    }
}
4

1 回答 1

0

放置 final 将清除您的错误。

final PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket
                            .getOutputStream())), true);

但是就像你说的你不想final,那为什么不声明out为全局变量呢?

// global variable
PrintWriter out;

.......

out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket
                                .getOutputStream())), true);
于 2013-01-24T02:18:32.820 回答