ServerSocket Accept() Example
Listens for a connection to be made to this socket and accepts it.
ServerSocketclass Accept() method example. This example shows you how to use Accept() method.This method Listens for a connection to be made to this socket and accepts it.
Here is the code:-
//PROGRAM FOR SERVER SIDE:-
/**
* @Program that Listens for a connection to be made to this socket and accepts it.
* Accept.java
* Author:-RoseIndia Team
* Date:-20-jun-2008
*/
import java.net.*;
import java.io.*;
import java.util.*;
public class Accept {
public static void main(String[] args) throws Exception {
//Creating server Socket
ServerSocket serverSocket = new ServerSocket(3333);
//Listens for a connection to be made to this socket and accepts it.
Socket clientSocket = serverSocket.accept();
//making object output Stream
ObjectOutputStream dateOut = null;
dateOut = new ObjectOutputStream(clientSocket.getOutputStream());
//writing the date
dateOut.writeObject(new Date());
dateOut.close();
System.out.println("Stream sent successfully");
//closing client socket
clientSocket.close();
serverSocket.close();
}
}
/*
*
PROGRAM FOR CLIENT SIDE:-
import java.net.*;
import java.io.*;
import java.util.*;
public class Client {
public static void main(String[] args) throws Exception {
//creating a new socket
Socket dateSocket = new Socket();
* //connecting the socket to desired address
dateSocket.connect(new InetSocketAddress("192.168.10.201", 3333));
//creating inputstream object
ObjectInputStream dateIn = new ObjectInputStream(dateSocket.getInputStream());
//getting the date of the server
Date serverDate = (Date) dateIn.readObject();
* //displaying the current date of the server
System.out.println("Current server time: " + serverDate);
}
}
*/
|
Output of the program:-
OUTPUT FOR CLIENT SIDE:-
Current server time: Mon Jun 23 12:06:39 IST 2008
OUTPUT FOR SERVER SIDE:-
Stream sent successfully |
|