Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.io.PrintWriter;
- import java.net.ServerSocket;
- import java.net.Socket;
- public class Server
- {
- public static void main(String[] args)
- {
- try
- {
- /* We create a server which listens to port no. 4040 of the computer. */
- ServerSocket ss = new ServerSocket(4040);
- /* Server stops at this line unless client connects to it. In a single threaded application like this, we
- * can handle only one client. The server continues further ONLY WHEN the client connects */
- Socket s = ss.accept();
- /* This stream is connected to the console to accept user input */
- BufferedReader readerForConsole = new BufferedReader(
- new InputStreamReader(System.in));
- /*
- * This stream is connected to the socket, to accept data from
- * server
- */
- BufferedReader readerForSocket = new BufferedReader(
- new InputStreamReader(s.getInputStream()));
- /*
- * This stream is connected to the socket, to write data to the
- * server
- */
- PrintWriter writerForSocket = new PrintWriter(s.getOutputStream());
- /*
- * now we can use standard readline() to read data from the server
- * and println() to write data to the server
- */
- while (true)
- {
- /* Read data from server */
- String dataFromServer = readerForSocket.readLine();
- /* write that data to console */
- System.out.println("< Response > " + dataFromServer);
- /* read some data from console */
- String dataFromConsole = readerForConsole.readLine();
- /*
- * write that data to socket so that server can read it. Please
- * note that using 'flush()' method is important in buffered
- * streams otherwise data is not sent to the other side unless
- * buffer is full.
- */
- writerForSocket.println(dataFromConsole);
- writerForSocket.flush();
- /*
- * This loops infinitely, please use cross on your command
- * prompt window to exit.
- *
- * Ideally we should close the I/O stearms as well as the socket
- * after completing our work. But that would be unreachable code
- * here as we are looping infinitely.
- *
- * Ideally we should do the following :
- *
- *
- * readerForConsole.close();
- *
- * readerForSocket.close();
- *
- * writerForSocket.close();
- *
- * s.close();
- */
- }
- }
- catch (IOException e)
- {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement