gpt4 book ai didi

java - 如何在 Java 中将 TCP 发送按钮放入循环中?

转载 作者:可可西里 更新时间:2023-11-01 02:54:50 25 4
gpt4 key购买 nike

我正在尝试创建一个具有编辑 TextView 和按钮的应用程序。此按钮将通过 TCP 连接将编辑文本中的任何内容发送到服务器。

我已经完成了编辑文本的发送,但是在我点击一次按钮后,应用程序崩溃了。我怎样才能把它放到一个循环中,这样我就可以发送多条消息了?这是我的来源

public class MainActivity extends Activity {

//Handler h;

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

final EditText eText = (EditText) findViewById(R.id.address);
final TextView tView = (TextView) findViewById(R.id.pagetext);
final Button button = (Button) findViewById(R.id.ButtonGo);
button.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
try {
Socket s = new Socket("192.168.0.117", 4447);
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
final BufferedWriter out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
//send output msg
String outMsg = ((EditText)findViewById(R.id.address)).getText().toString().trim();
out.write(outMsg);
out.flush();
Log.i("TcpClient", "sent: " + outMsg);
} catch (UnknownHostException e) {
tView.setText(e.toString());
Log.v("Tcp",e.toString());
} catch (IOException e) {
tView.setText(e.toString());
Log.v("Tcp",e.toString());
}catch (Exception e) {
tView.setText(e.toString());

}
}
});
}
}

最佳答案

我通过使用两个不同的按钮来完成此操作。一个连接按钮和一个发送消息按钮。我认为当服务器试图重新创建套接字时,TCP 连接中断并且服务器捕获异常并开始崩溃。这是新代码。

            bConnect.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
try {
Socket s = new Socket("192.168.0.117", 4447);
out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
} catch (UnknownHostException e) {
tView.setText(e.toString());
Log.v("Tcp",e.toString());
} catch (IOException e) {
tView.setText(e.toString());
Log.v("Tcp",e.toString());
}catch (Exception e) {
tView.setText(e.toString());

}
}
});

bSend.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
try {
String outMsg = ((EditText)findViewById(R.id.address)).getText().toString().trim();
out.write(outMsg);
out.flush();
Log.i("TcpClient", "sent: " + outMsg);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


finally{

}
}


});

关于java - 如何在 Java 中将 TCP 发送按钮放入循环中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14097634/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com