Android客户端
import android.os.Bundle; import android.app.Activity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class MainActivity extends Activity { private TextView textView; private EditText editText; private PrintWriter printWriter; private ExecutorService executorService = Executors.newSingleThreadExecutor(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = findViewById(R.id.textView); editText = findViewById(R.id.editText); Button button = findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String message = editText.getText().toString(); if (!message.isEmpty()) { printWriter.println(message); editText.setText(""); } } }); executorService.submit(new Runnable() { @Override public void run() { try { Socket socket = new Socket("192.168.1.100", 9999); // 替换为服务器IP地址和端口号 printWriter = new PrintWriter(socket.getOutputStream(), true); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream())); while (!Thread.currentThread().isInterrupted()) { String line = bufferedReader.readLine(); if (line != null) { final String finalLine = line; runOnUiThread(new Runnable() { @Override public void run() { textView.append(finalLine + " "); } }); } } } catch (Exception e) { e.printStackTrace(); } } }); } }
服务器端代码
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; public class Server { public static void main(String[] args) { try { ServerSocket serverSocket = new ServerSocket(9999); // 端口号与客户端保持一致 System.out.println("服务器已启动,等待连接..."); while (true) { Socket socket = serverSocket.accept(); System.out.println("客户端已连接:" + socket); new Thread(new Runnable() { @Override public void run() { try { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true); String line; while ((line = bufferedReader.readLine()) != null) { System.out.println("收到消息:" + line); printWriter.println("服务器已收到:" + line); // 回显消息给客户端 } } catch (Exception e) { e.printStackTrace(); } finally { try { socket.close(); } catch (Exception e) { e.printStackTrace(); } } } }).start(); } } catch (Exception e) { e.printStackTrace(); } } }
代码展示了一个简单的Android客户端与Java服务器端的TCP Socket通信示例,客户端可以发送消息到服务器,服务器接收后回显消息给客户端,实际项目中需要根据具体需求进行修改和完善,例如添加错误处理、优化性能等。
到此,以上就是小编对于“app和服务器通信源码”的问题就介绍到这了,希望介绍的几点解答对大家有用,有任何问题和不懂的,欢迎各位朋友在评论区讨论,给我留言。
原创文章,作者:K-seo,如若转载,请注明出处:https://www.kdun.cn/ask/719329.html