简历网站后怎样才能被谷歌 百度收录吗,网站分析论文,北京网站建设公司空间续费北京,win10 wordpress安装教程以下是使用 Android Studio 基于 Java 语言编写一个简单的 Android APP 实现远程通信#xff08;这里以 TCP 通信为例#xff09;的代码示例#xff0c;包含基本的通信界面以及发送和接收消息功能。
1. 创建项目
打开 Android Studio#xff0c;新建一个 Empty Activity …以下是使用 Android Studio 基于 Java 语言编写一个简单的 Android APP 实现远程通信这里以 TCP 通信为例的代码示例包含基本的通信界面以及发送和接收消息功能。
1. 创建项目
打开 Android Studio新建一个 Empty Activity 的 Android 项目填写好项目相关信息后等待项目构建完成。
2. 设计界面布局activity_main.xml
在res/layout目录下的activity_main.xml文件中设计如下简单布局包含一个用于输入消息的编辑文本框、发送按钮以及一个用于显示接收消息的文本视图
?xml version1.0 encodingutf-8?LinearLayout xmlns:androidhttp://schemas.android.com/apk/res/androidandroid:layout_widthmatch_parentandroid:layout_heightmatch_parentandroid:orientationverticalandroid:padding16dpEditTextandroid:idid/editTextMessageandroid:layout_widthmatch_parentandroid:layout_heightwrap_contentandroid:padding16dpandroid:layout_marginTop16dpandroid:layout_marginLeft0dpandroid:hint输入要发送的消息 /TextViewandroid:idid/textViewReceivedMessagesandroid:layout_widthmatch_parentandroid:layout_heightwrap_contentandroid:layout_marginTop64dpandroid:layout_marginLeft0dpandroid:text接收的消息 /Buttonandroid:idid/buttonSendandroid:layout_widthwrap_contentandroid:layout_heightwrap_contentandroid:layout_marginTop100dpandroid:layout_marginLeft128dpandroid:text发送 //LinearLayout
3. 编写远程通信及逻辑代码MainActivity.java
在MainActivity.java文件中添加以下代码来实现 TCP 通信以及相关的界面交互逻辑
java
package com.example.myapplication;import android.os.Bundle;import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;import androidx.appcompat.app.AppCompatActivity;
import java.io.FileOutputStream;
import java.io.OutputStream;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;public class MainActivity extends AppCompatActivity {private EditText editTextMessage;private TextView textViewReceivedMessages;private Socket socket;private BufferedReader reader;private BufferedWriter writer;Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);EdgeToEdge.enable(this);setContentView(R.layout.activity_main);editTextMessage findViewById(R.id.editTextMessage);Button buttonSend findViewById(R.id.buttonSend);textViewReceivedMessages findViewById(R.id.textViewReceivedMessages);// 尝试连接服务器这里假设服务器IP是192.168.0.100端口是8888根据实际情况修改new Thread(() - {try {socket new Socket(192.168.1.6, 8888);reader new BufferedReader(new InputStreamReader(socket.getInputStream()));writer new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));// 开启线程接收服务器消息receiveMessages();} catch (IOException e) {e.printStackTrace();}}).start();buttonSend.setOnClickListener(new View.OnClickListener() {Overridepublic void onClick(View v) {String message editTextMessage.getText().toString().trim();if (!message.isEmpty()) {new Thread(() - {try {writer.write(message \n);writer.flush();} catch (IOException e) {e.printStackTrace();}}).start();}}});}private void receiveMessages() {try {while (true) {String receivedMessage reader.readLine();if (receivedMessage! null) {runOnUiThread(() - {textViewReceivedMessages.append(\n receivedMessage);});}}} catch (IOException e) {e.printStackTrace();}}Overrideprotected void onDestroy() {super.onDestroy();try {if (socket! null) {socket.close();}if (reader! null) {reader.close();}if (writer! null) {writer.close();}} catch (IOException e) {e.printStackTrace();}}
}代码解释如下
在onCreate方法中 首先通过findViewById方法找到界面布局中的各个控件。然后开启一个新线程去尝试连接远程服务器IP 和端口按需修改成功连接后获取输入输出流并开启receiveMessages方法所在的线程用于接收服务器发来的消息。给发送按钮设置点击监听器当点击按钮时获取编辑文本框中的消息内容若不为空则开启新线程将消息发送给服务器注意要按协议添加换行符等规范格式这里简单用\n分隔消息。receiveMessages方法在一个循环中不断读取服务器发送过来的消息每读取到一条消息通过runOnUiThread方法将消息更新显示到界面的文本视图上因为 Android 中涉及 UI 更新操作要在主线程执行。onDestroy方法在 Activity 销毁时关闭相关的套接字、输入输出流等资源防止资源泄漏。
4. 添加网络权限 在AndroidManifest.xml文件中添加网络访问权限确保 APP 可以进行网络通信
xml
manifest xmlns:androidhttp://schemas.android.com/apk/res/androidpackagecom.example.remotecommunicationappuses-permission android:nameandroid.permission.INTERNET /application.../application/manifest请注意
上述代码中服务器的 IP 地址和端口号示例中为192.168.0.100和8888要根据实际部署运行的服务器情况进行修改。这只是一个简单的示例实现实际应用中可以根据需求扩展功能比如添加更多的界面交互、错误处理机制、加密通信等。还可以考虑使用更高级的网络通信框架来简化开发流程以及增强稳定性等。 运行这个 Android APP 后在界面输入消息点击发送就能将消息发送给对应的服务器同时可以接收服务器返回的消息并显示在界面上。 界面 这里还需要要一个电脑做服务器接受和发送消息
python
import socket# 创建套接字对象
server_socket socket.socket(socket.AF_INET, socket.SOCK_STREAM)# 绑定IP地址和端口
server_address (192.168.1.6, 8888)
server_socket.bind(server_address)# 监听连接
server_socket.listen(5)print(Server is listening on {}:{}.format(*server_address))while True:# 接受客户端连接client_socket, client_address server_socket.accept()print(Connected by, client_address)try:while True:# 接收客户端发送的数据data client_socket.recv(1024)if data:print(Received data:, data.decode(utf-8))# 发送响应数据给客户端这里简单回复一个确认消息#client_socket.sendall(Message received successfully!.encode(utf-8))server_socket.sendall(Message received successfully!.encode(utf-8))else:breakfinally:# 关闭客户端连接套接字client_socket.close()最终结果,我现在只能单向发送一旦回复消息就必然抛出异常。如有方法改正还请指出谢谢