我需要你在下面的代码中加入一些功能,public class MainActivity extends AppCompatActivity { private EditText ipEditText; private EditText portEditText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ipEditText = findViewById(R.id.ipEditText); portEditText = findViewById(R.id.portEditText); Button connectButton = findViewById(R.id.connectButton); connectButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String ip = ipEditText.getText().toString(); int port = Integer.parseInt(portEditText.getText().toString()); try { Socket socket = new Socket(ip, port); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); String message = in.readLine(); // 处理接收到的消息 } catch (IOException e) { e.printStackTrace(); } } }); }功能如下:在点击连接后,不会退出程序,主页面中有一个窗口可以事实监听显示端口下的消息
时间: 2024-01-23 13:01:47 浏览: 206
好的,根据您的需求,我可以在`MainActivity`的`onClick`方法中添加相应的功能:
```java
public class MainActivity extends AppCompatActivity {
private EditText ipEditText;
private EditText portEditText;
private TextView messageTextView;
private Socket socket;
private BufferedReader in;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ipEditText = findViewById(R.id.ipEditText);
portEditText = findViewById(R.id.portEditText);
Button connectButton = findViewById(R.id.connectButton);
messageTextView = findViewById(R.id.messageTextView);
connectButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String ip = ipEditText.getText().toString();
int port = Integer.parseInt(portEditText.getText().toString());
try {
socket = new Socket(ip, port);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// 在主页面中的窗口中实时显示消息
new Thread(new Runnable() {
@Override
public void run() {
try {
while (true) {
String message = in.readLine();
if (message == null) {
break;
}
runOnUiThread(new Runnable() {
@Override
public void run() {
messageTextView.append(message + "\n");
}
});
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
try {
if (in != null) {
in.close();
}
if (socket != null) {
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
在这段代码中,我添加了一个`TextView`控件来显示接收到的消息,并在`onClick`方法中添加了一个新的线程来实时监听客户端发来的消息,并将这些消息显示在`TextView`控件中。这里我使用了`socket.getInputStream()`方法来获取与服务器连接的输入流,并使用`in.readLine()`方法来接收服务器发来的消息。当接收到消息时,我使用了`runOnUiThread`方法来在主线程中更新`TextView`控件,以实现实时更新显示。
同时,我也添加了`onDestroy`方法,在程序退出时关闭输入流和socket连接,以释放资源。
阅读全文