Junior — Middle
Millised komponendid rakendavad socket-ühenduste funktsionaalsust süsteemis?
sobes.tech AI
Vastus AI-lt
In Android, the functionality of socket connections is usually implemented using the following components:
- Socket from the Java API (
java.net.Socket) — the base class for creating TCP connections. - ServerSocket — for the server part, to listen for incoming connections.
- InputStream and OutputStream — for reading and writing data through the socket.
- AsyncTask, Thread or Coroutine — to perform network operations in a separate thread, so as not to block the UI.
Libraries such as OkHttp for WebSocket connections can also be used, which simplify working with sockets.
Example of creating a TCP socket in a separate thread:
new Thread(() -> {
try (Socket socket = new Socket("example.com", 1234)) {
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
// reading and writing data
} catch (IOException e) {
e.printStackTrace();
}
}).start();