Sunday, 20 January 2013

TCP Server-JAVA


// tcpServer.java by fpont 3/2000
// usage : java tcpServer <port number>.
// default port is 1500.
// connection to be closed by client.
// this server handles only 1 connection.

import java.net.*;
import java.io.*;

public class tcpServer {
    
public static void main(String args[]) {
 
ServerSocket server_socket=null;
BufferedReader input;
   
 try {
     
     server_socket = new ServerSocket(0);
     System.out.println("Server waiting for client on port " + 
          server_socket.getLocalPort());
     
     // server infinite loop
      Socket socket = server_socket.accept();
  System.out.println("New connection accepted " +
       socket.getInetAddress() +
       ":" + socket.getPort());
  input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
  // print received data
  try {
      while(true) {
    String message = input.readLine();
    if (message.equals("quit")) break;
    System.out.println(message.toUpperCase());
      }
  }
  catch (IOException e) {
      System.out.println(e);
  }

  // connection closed by client
  try {
      socket.close();
      System.out.println("Connection closed by client");

            server_socket.close();
      System.exit(1);
  }
  catch (IOException e) {
      System.out.println(e);
  }


 }
 catch (IOException e) {
     System.out.println(e);
    }
}}