要测试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" />