|
|
|
All the java programs communicate with a help of a programming abstraction which is called a socket. It basically denotes the end point of any network communication. The benefit of having a file abstraction is that all the details related to the storage of file, their location, how they are read and written is all hidden under this abstraction and this as a result gives the programmer a very easy and a simple functional programming interface.
Most applications do not care how data is actually transmitted in the network. Applications identify the address of the peer entity and then use the sockets interface to read and write data from and to ther peer. Sockets combine the implementation of network and transport layer protocols providing applications with a simple read/write interface. Java provides to types of sockets :
1. Server Sockets
2. Sockets
|
| Server Sockets
|
|
Example for ServerSocket
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerSocketExample {
public static void main(String[] args) throws IOException {
InetAddress address = InetAddress.getByName("127.0.0.1");
ServerSocket server = new ServerSocket(5464, 0, address);
System.out.println(server.getInetAddress().getHostAddress());
System.out.println("Listening");
Socket clientSocket = server.accept();
System.out.println("Connection Accepted...");
BufferedReader reader =
new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
System.out.println(reader.readLine());
}
}
|
| Sockets
|
|
Example for Socket
import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class SocketExample {
public static void main(String[] args) throws IOException {
Socket socket = null;
PrintWriter printWriter = null;
InetAddress address = InetAddress.getByName("127.0.0.1");
try {
socket = new Socket(address, 5464);
printWriter = new PrintWriter(socket.getOutputStream(),
true);
printWriter.println("Hello MeshPlex");
printWriter.flush();
}
catch (UnknownHostException e) {
System.out.println("Don't know about host: 127.0.0.1");
}
catch (IOException e) {
System.out.println("Couldn't get I/O for "
+ "the connection to: 127.0.0.1");
}
printWriter.close();
socket.close();
}
}
|
|