Socket programming in Java PDF
Socket programming in Java PDF
Here is a comprehensive guide to socket programming in Java in the form of a PDF:
Socket Programming in Java: A Comprehensive Guide
Introduction
Socket programming is an essential part of network communication, allowing programs to communicate with each other over a network. This tutorial provides a step-by-step guide on how to create socket programming in Java.
What are Sockets?
Sockets are endpoints for communication between two devices (computer, phone, etc.) in a network. They provide a way for different processes (programs) to communicate with each other. A socket is like an end point where the program can read from or write to.
Types of Sockets
There are two types of sockets:
Stream-oriented Socket: This type of socket allows data to be sent and received as streams of bytes. Datagram-oriented Socket (also known as UDP Socket): This type of socket sends and receives datagrams, which are packets of data with a maximum size.Creating Sockets in Java
To create sockets in Java, we use the java.net
package, specifically the Socket
, ServerSocket
, DatagramPacket
, and DatagramSocket
classes.
Client Side (Sender)
Import necessary packages:import java.net.*;
Create a new socket: Socket client = new Socket("serverHost", portNumber);
Send data over the socket: client.getOutputStream().write(data);
Close the socket: client.close();
Server Side (Receiver)
Import necessary packages:import java.net.*;
Create a new server socket: ServerSocket server = new ServerSocket(portNumber);
Listen for incoming connections: Socket client = server.accept();
Receive data from the client: byte[] receivedData = new byte[1024]; client.getInputStream().read(receivedData);
Close the socket: client.close();
Datagram Sockets (UDP)
Import necessary packages:import java.net.*;
Create a new datagram socket: DatagramSocket dgramSock = new DatagramSocket();
Send data over the socket: dgramSock.send(new DatagramPacket(data, length));
Receive data from the client: DatagramPacket receivedData = new DatagramPacket(receivedData, receivedData.length);
Close the socket: dgramSock.close();
Best Practices
Always close sockets after use to prevent resource leaks. Handle exceptions and errors properly to ensure robustness. Use thread pools for concurrent processing.Conclusion
In this comprehensive guide, we have learned how to create socket programming in Java using stream-oriented and datagram-oriented sockets. By following the best practices and handling exceptions, you can create reliable and efficient network communication programs in Java.
PDF: Socket Programming in Java
Please note that this is a basic guide and you may want to consider advanced topics such as socket options, non-blocking sockets, and multiplexing.
Client server socket programming in java example
Here is an example of client-server socket programming in Java:
Server Side Code
import java.net.*;
import java.io.*;
public class Server {
public static void main(String[] args) throws IOException {
// Create a server socket
ServerSocket server = new ServerSocket(8000);
System.out.println("Server started. Listening for incoming connections...");
while (true) {
// Wait for a client to connect
Socket socket = server.accept();
System.out.println("Incoming connection from " + socket.getInetAddress());
// Create a separate thread to handle the client request
Thread t = new ServerThread(socket);
t.start();
}
}
}
class ServerThread extends Thread {
Socket socket;
public ServerThread(Socket s) {
this.socket = s;
}
public void run() {
try {
// Read from the client
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println("Received message from client: " + inputLine);
}
// Send a response back to the client
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println("Hello, client!");
} catch (IOException e) {
System.out.println("Error handling client request");
} finally {
try {
socket.close();
} catch (Exception e) {
// Ignore exception on close
}
}
}
}
Client Side Code
import java.net.*;
import java.io.*;
public class Client {
public static void main(String[] args) throws IOException {
// Create a client socket
Socket socket = new Socket("localhost", 8000);
System.out.println("Connected to the server");
// Send a message to the server
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out.println("Hello, server!");
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println("Received response from server: " + inputLine);
}
// Close the connection
socket.close();
}
}
In this example, the server creates a ServerSocket
and listens for incoming connections. When a client connects, it creates a separate thread to handle the client's request. The thread reads from the client and sends a response back.
On the client side, it creates a Socket
to connect to the server. It then sends a message to the server and receives any responses. Finally, it closes the connection.
This is a basic example of client-server socket programming in Java. In a real-world scenario, you would likely want to add more error handling and possibly use more advanced networking techniques.
Note: Make sure to run the server code first, then the client code. The server will print out messages as clients connect and send requests.