我在android中有一个套接字程序,我想通过单击客户端上的按钮发送命令或文本消息。并根据按下的按钮发送不同的文本消息。但我得到关于“out”PrintWriter对象的编译器错误消息 PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket .getOutputStream())),true);
如果我在onclick监听器中使用此“out”,我该如何修复此编译器错误?我真的不想把它作为编译器推荐的最终变量作为修复。
这里是下面显示的代码,在run()方法中有两个onclick按钮监听器,用于通过套接字从客户端发送按摩到服务器android app
如果您点击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;
}
}
}
答案 0 :(得分:0)
决赛将清除您的错误。
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);