在Android开发中,Socket通信是一种常见的实现网络功能的方式,通过Socket编程,可以实现客户端与服务器之间的双向通信,从而实现即时通讯、数据同步等功能,本文将详细介绍如何在Android平台上进行基于Socket的通信开发。
一、
Socket是一种提供网络通信能力的编程接口,通过它,应用程序可以在网络上进行数据传输,在Android中,我们可以使用java.net
包下的Socket
和ServerSocket
类来创建客户端和服务器端,进行双向通信。
二、创建Socket连接
1. 客户端建立Socket连接
在客户端,需要创建一个Socket
对象并连接到服务器的IP地址和端口:
try { String serverIpAddress = "192.168.1.1"; // 服务器IP地址 int serverPort = 8080; // 服务器端口 Socket socket = new Socket(serverIpAddress, serverPort); // 连接成功,可以进行后续操作 } catch (IOException e) { e.printStackTrace(); }
2. 服务器端建立ServerSocket连接
在服务器端,需要创建一个ServerSocket
对象并绑定到指定的端口,等待客户端的连接:
try { int port = 8080; // 服务器端口 ServerSocket serverSocket = new ServerSocket(port); System.out.println("服务器已启动,等待客户端连接..."); Socket clientSocket = serverSocket.accept(); // 阻塞,直到有客户端连接 // 处理客户端连接 } catch (IOException e) { e.printStackTrace(); }
三、发送信息
建立连接后,可以通过OutputStream
向服务器发送数据:
try { OutputStream outputStream = socket.getOutputStream(); PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream)); // 发送消息 writer.println("Hello, Server!"); writer.flush(); } catch (IOException e) { e.printStackTrace(); }
四、接收信息
通过InputStream
可以从服务器接收数据:
try { InputStream inputStream = socket.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); // 读取服务器发送的消息 String receivedMessage = reader.readLine(); // 处理接收到的消息 } catch (IOException e) { e.printStackTrace(); }
五、完整示例
以下是一个简单的示例工具类,用于处理连接、发送和接收消息:
import java.io.*; import java.net.*; public class SocketUtils { private Socket socket = null; private InputStream mInputStream = null; private BufferedReader reader = null; private PrintWriter writer = null; private OnMessageReceivedListener messageListener; public SocketUtils(String serverIpAddress, int serverPort) { try { socket = new Socket(); SocketAddress socAddress = new InetSocketAddress(serverIpAddress, serverPort); socket.connect(socAddress, 800); socket.setKeepAlive(true); mInputStream = socket.getInputStream(); reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true); } catch (IOException e) { e.printStackTrace(); } } public void setOnMessageReceivedListener(OnMessageReceivedListener listener) { this.messageListener = listener; } public void startListening() { new Thread(new Runnable() { @Override public void run() { char[] buffer = new char[1024]; while (true) { try { int len = mInputStream.read(buffer); if (len > 0) { if (messageListener != null) { messageListener.onMessageReceived(new String(buffer, 0, len)); } } else { break; } } catch (IOException e) { e.printStackTrace(); } } } }).start(); } public interface OnMessageReceivedListener { void onMessageReceived(String message); } }
六、环境配置及权限要求
确保已安装Android Studio。
将手机与电脑连接在同一局域网内,或者手机给电脑开热点。
在手机的“开发者选项”中打开“USB调试”,并通过USB线连接手机和电脑。
在Android Studio中选择“Terminal窗口”或“cmd窗口”,输入命令实现无线连接,具体步骤如下:
adb devices
:查看设备号。
adb -s <设备号> tcpip <端口号>
或adb tcpip <端口号>
:设置TCP/IP端口。
adb connect <手机IP地址:<端口号>
:连接设备。
adb disconnect <手机IP地址:<端口号>
:断开连接。
2. 所需权限
在应用的清单文件中添加以下权限:
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
1. 服务端代码
package com.example.sockettest; import android.os.Handler; import android.os.Message; import android.util.Log; import android.widget.Toast; import java.io.*; import java.net.*; import java.util.concurrent.*; import java.util.*; public class MyServerSocket { private static final int PORT = 9999; private List<Socket> mList = new ArrayList<>(); private ServerSocket server = null; private ExecutorService mExecutorService = null; private String receiveMsg; private String sendMsg; public MyServerSocket() { try { server = new ServerSocket(PORT); mExecutorService = Executors.newCachedThreadPool(); System.out.println("服务器已启动..."); while (true) { Socket client = server.accept(); mList.add(client); mExecutorService.execute(new Service(client)); } } catch (Exception e) { e.printStackTrace(); } } class Service implements Runnable { private Socket client; private PrintWriter printWriter; private BufferedReader bufferedReader; private String receiveMsg; private String sendMsg; private boolean isRunning = true; public Service(Socket client) { this.client = client; try { printWriter = new PrintWriter(new OutputStreamWriter(client.getOutputStream()), true); bufferedReader = new BufferedReader(new InputStreamReader(client.getInputStream())); } catch (IOException e) { e.printStackTrace(); } } @Override public void run() { while (isRunning) { try { receiveMsg = bufferedReader.readLine(); // 从客户端接收消息 if (receiveMsg != null) { System.out.println("收到消息:" + receiveMsg); // 打印收到的消息 sendMsg = "服务器回复:" + receiveMsg; // 构建回复消息 printWriter.println(sendMsg); // 发送回复消息给客户端 } else { isRunning = false; // 如果收到null,则退出循环 } } catch (IOException e) { e.printStackTrace(); } } try { client.close(); // 关闭客户端连接 } catch (IOException e) { e.printStackTrace(); } finally { mList.remove(client); // 从列表中移除客户端连接 } } } }
2. 客户端代码
package com.example.sockettest; import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; import android.view.View; import java.io.*; import java.net.*; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.os.AsyncTask; import android.widget.Toast; import java.util.concurrent.*; import java.util.*; public class MainActivity extends AppCompatActivity { private EditText editText; private Button btnSend; private TextView textView; private Socket socket; private PrintWriter printWriter; private BufferedReader bufferedReader; private String receiveMsg; private String sendMsg; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); editText = findViewById(R.id.editText); btnSend = findViewById(R.id.btnSend); textView = findViewById(R.id.textView); btnSend.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { sendMsg = editText.getText().toString(); new SendTask().execute(sendMsg); } }); new ReceiveTask().execute(); } class SendTask extends AsyncTask<String, Void, Void> { @Override protected Void doInBackground(String... msgs) { try { if (socket == null) { socket = new Socket("192.168.1.32", 9999); printWriter = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true); } printWriter.println(msgs[0]); return null; } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); } } class ReceiveTask extends AsyncTask<Void, Void, Void> { @Override protected Void doInBackground(Void... voids) { try { if (bufferedReader == null) { bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream())); } receiveMsg = bufferedReader.readLine(); return null; } catch (IOException e) { e.printStackTrace(); } } @Override protected void onProgressUpdate(Void... values) { super.onProgressUpdate(values); } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); if (receiveMsg != null) { textView.setText("服务器回复:" + receiveMsg); } } } }```
小伙伴们,上文介绍了“android开发基于socket通信程序”的内容,你了解清楚吗?希望对你有所帮助,任何问题可以给我留言,让我们下期再见吧。
原创文章,作者:K-seo,如若转载,请注明出处:https://www.kdun.cn/ask/625647.html