要測試Android SocketChannel的正確性,你可以編寫一個簡單的測試程序來執行以下操作:
以下是一個簡單的測試程序示例:
import android.os.Build;
import androidx.annotation.RequiresApi;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
public class SocketChannelTest {
@RequiresApi(api = Build.VERSION_CODES.P)
public static void main(String[] args) {
SocketChannel socketChannel = null;
try {
// 1. 創建一個SocketChannel實例
socketChannel = SocketChannel.open();
socketChannel.configureBlocking(false);
// 2. 連接到服務器
InetSocketAddress serverAddress = new InetSocketAddress("your_server_address", your_server_port);
socketChannel.connect(serverAddress);
// 3. 向服務器發送數據
String message = "Hello, Server!";
ByteBuffer buffer = ByteBuffer.wrap(message.getBytes());
socketChannel.write(buffer);
// 4. 從服務器接收數據
buffer.clear();
int bytesRead = socketChannel.read(buffer);
if (bytesRead > 0) {
buffer.flip();
byte[] receivedData = new byte[buffer.remaining()];
buffer.get(receivedData);
String receivedMessage = new String(receivedData);
System.out.println("Received from server: " + receivedMessage);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
// 5. 關閉連接
try {
if (socketChannel != null && socketChannel.isOpen()) {
socketChannel.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
請注意,你需要將your_server_address
和your_server_port
替換為你要連接的服務器的實際地址和端口。此外,由于Android SocketChannel的限制,你可能需要在AndroidManifest.xml中添加INTERNET權限:
<uses-permission android:name="android.permission.INTERNET" />