KillianMills

Server.java

Nov 3rd, 2014
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.72 KB | None | 0 0
  1. import java.net.*;
  2. import java.io.*;
  3. import java.util.Date;
  4. import java.text.DateFormat;
  5. import java.text.SimpleDateFormat;
  6.  
  7. // One thread per connection, this is it
  8. class ServerThread extends Thread {
  9.  
  10.     // The socket passed from the creator
  11.     private Socket socket = null;
  12.  
  13.     public ServerThread(Socket socket) {
  14.  
  15.         this.socket = socket;
  16.  
  17.     }
  18.  
  19.     // Handle the connection
  20.     public void run() {
  21.  
  22.         try {
  23.  
  24.         // Attach a printer to the socket's output stream
  25.         PrintWriter socketOut = new PrintWriter(socket.getOutputStream(), true);
  26.  
  27.         // Get the date and time
  28.         DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss dd/MM/yyyy");
  29.         Date date = new Date();
  30.  
  31.         // Send the date and time to the client
  32.         socketOut.println(dateFormat.format(date));
  33.  
  34.         // Close things
  35.         socketOut.close();
  36.         socket.close();
  37.  
  38.     } catch (IOException e) {
  39.  
  40.         e.printStackTrace();
  41.  
  42.         }
  43.     }
  44. }
  45.  
  46. // The server
  47. public class Server {
  48.  
  49.     public static void main(String[] args) throws IOException {
  50.  
  51.     // The server socket, connections arrive here
  52.         ServerSocket serverSocket = null;
  53.  
  54.         try {
  55.  
  56.         // Listen on on port 7777
  57.             serverSocket = new ServerSocket(7777);
  58.  
  59.         } catch (IOException e) {
  60.  
  61.             System.err.println("Could not listen on port: 7777");
  62.             System.exit(-1);
  63.  
  64.         }
  65.  
  66.     // Loop forever
  67.         while (true) {
  68.  
  69.         /*
  70.          * Several things going on with this line of code:
  71.          * 1. Accept a connection (returns a new socket)
  72.          * 2. Create a new thread of type ServerThread
  73.          * 3. Call start on the new thread
  74.          */
  75.         new ServerThread(serverSocket.accept()).start();
  76.         }
  77.     }
  78. }
Advertisement
Add Comment
Please, Sign In to add comment