Java Socket Programming for Client-Server Communication
Classified in Computers
Written on in English with a size of 2.62 KB
Java Socket Implementation
Client-Server Socket Class (`Misocket`)
Constructor for Server (`Misocket(int port)`):
- Initializes a `ServerSocket` with the specified port.
- Waits for and accepts a client connection using `serverSocket.accept()`.
- Obtains input and output streams from the accepted client socket.
Constructor for Client (`Misocket(String ip, int port)`):
- Creates a `Socket` to connect to the specified IP address and port.
- Obtains input and output streams for communication.
Core Functionality
Sending and Receiving Strings:
- `dos.writeUTF(cadena); dos.flush();` to send a string.
- `cadena = dis.readUTF(); return cadena;` to receive a string.
Sending and Receiving Integers:
- `dos.writeInt(tam);` to send an integer.
- `tam = dis.readInt(); return tam;` to receive an integer.
Array Handling:
- `public void enviar_array(Array array)`: Sends an array of bytes.
- `public Array recibir_array(int tam)`: Receives an array of bytes of a specified size.
Array Class (`Array`)
- Stores data in a `byte[]` array.
- Constructor: `public Array(int tam)` initializes the byte array with a given size.
- `public int tam_array()`: Returns the maximum size of the array.
- `public byte[] obtenerArray()`: Returns the underlying byte array.
- `actualizartam(int nuevoTam)`: Updates the array's effective size.
- `public byte obtenervalor(int pos)`: Retrieves a byte at a specific position.
- `public void insertarelemento(byte valor, int pos)`: Inserts a byte at a specific position.
File Handling (`Fichero`)
- Represents a file with a given name.
- `public Array volcar_fich_array(int tam)`: Reads data from a file into an `Array` object.
- `public void volcar_array_fichero(Array array)`: Writes data from an `Array` object to a file.
Stream Management
- Methods for opening and closing input/output streams (e.g., `abrestreams_l`, `cerrrar_streams`, `abrir strams`, `cerrarstreams_e`).
- Includes `FileInputStream`, `BufferedInputStream`, `DataInputStream`, `FileOutputStream`, `BufferedOutputStream`, and `DataOutputStream`.
Closing Connections
- `if(dis!=null) dis.close();`: Closes input streams.
- Similar logic applies to other streams (`bis`, `fis`, `fos`, `bos`, `dos`).
Example Usage (`main`)
- Client: `Misocket sock = new Misocket("localhost", 5000);`
- Server: `Misocket sock = new Misocket(5000);`