域名套接字(Domain Socket),也称为Unix域套接字(Unix Domain Socket),是一种在同一台机器上的进程间通信(IPC)机制。它允许不同进程通过文件系统路径进行通信,类似于网络套接字,但不需要网络协议栈。
以下是一个简单的Android中使用域名套接字的示例:
import android.os.Bundle;
import android.util.Log;
import androidx.appcompat.app.AppCompatActivity;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "DomainSocketServer";
private static final String SOCKET_PATH = "/tmp/mysocket";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(() -> {
try {
ServerSocket serverSocket = new ServerSocket(SOCKET_PATH);
Log.d(TAG, "Server started");
while (true) {
Socket clientSocket = serverSocket.accept();
Log.d(TAG, "Client connected");
// Handle client communication
// ...
clientSocket.close();
}
} catch (IOException e) {
Log.e(TAG, "Server error", e);
}
}).start();
}
}
import android.os.Bundle;
import android.util.Log;
import androidx.appcompat.app.AppCompatActivity;
import java.io.IOException;
import java.net.Socket;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "DomainSocketClient";
private static final String SOCKET_PATH = "/tmp/mysocket";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(() -> {
try {
Socket socket = new Socket(SOCKET_PATH);
Log.d(TAG, "Connected to server");
// Handle server communication
// ...
socket.close();
} catch (IOException e) {
Log.e(TAG, "Client error", e);
}
}).start();
}
}
原因:
解决方法:
// 确保路径存在
File socketFile = new File(SOCKET_PATH);
if (!socketFile.exists()) {
socketFile.createNewFile();
}
// 设置权限
socketFile.setReadable(true, false);
socketFile.setWritable(true, false);
原因:
解决方法:
// 发送数据
OutputStream outputStream = socket.getOutputStream();
outputStream.write("Hello".getBytes("UTF-8"));
// 接收数据
InputStream inputStream = socket.getInputStream();
byte[] buffer = new byte[1024];
int bytesRead = inputStream.read(buffer);
String receivedData = new String(buffer, 0, bytesRead, "UTF-8");
希望这些信息对你有所帮助!如果有更多问题,请随时提问。
领取专属 10元无门槛券
手把手带您无忧上云