Socket Programming in Java
Understanding Sockets
- Definition: A socket is an endpoint for communication between two machines.
- Binding to Port: Sockets are bound to a port number, allowing the TCP layer to identify the intended application for the data.
- Java Networking: The
java.netpackage provides necessary classes for network programming in Java.
Server Side Implementation
Import Statements
- Necessary classes from
java.ioandjava.netpackages are imported for input/output operations and network communications.
Server Class Declaration
- Main Method: Entry point of the application, where execution starts.
Try-Catch Block
- Utilized to handle exceptions that may arise, particularly IOExceptions during the execution of the code.
Creating ServerSocket
- A
ServerSocketobject is created, which listens on a specific port (e.g., port 5000) to accept incoming client connections. - A message is printed to indicate the server is ready to accept connections.
Accepting Client Connections
- The server waits and accepts connections from clients; upon connection, it returns a
Socketobject representing the established connection.
Setting Up Streams
- Receiving Messages: Input and output streams are established to communicate with the client. This enables the server to read messages sent by the client and send responses back.
Closing Streams and Sockets
- Proper closure of input and output streams and sockets to release resources and terminate the connection with the client.
Catch Block
- Handles IOExceptions during the try block and prints stack trace for debugging purposes.
Printing Client's Message
- The server prints the received client message to the console and sends a response back through the output stream.
Client Side Implementation
Creating a Client Socket
- Use the
Socketclass in Java to represent the client-side socket, enabling communication with the server.
Setting Up Input and Output Streams
- Input Stream:
BufferedReader inis created to read messages from the server.
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
- Output Stream:
PrintWriter outis used to send messages to the server.
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
Sending and Receiving Messages
- To send a message to the server:
out.println("Hello from client!");
- To read the server's response:
String response = in.readLine();
System.out.println("Server: " + response);
Closing Streams and Socket
- Properly close streams and sockets after communication:
in.close();
out.close();
socket.close();
Running the Code
Steps to execute:
- Compile both server and client classes.
- Start the server first.
- Run the client to see the communication in action.
Messages indicating communication will be shown in the console.