|
| 1 | +importjava.io.*; |
| 2 | +importjava.net.*; |
| 3 | + |
| 4 | +publicclassServer { |
| 5 | +publicstaticvoidmain(String[]args) { |
| 6 | +try { |
| 7 | +// Creating a ServerSocket object to listen on a specific port |
| 8 | +ServerSocketss =newServerSocket(2444); |
| 9 | + |
| 10 | +// Asking user to enter the port address for the server to listen on |
| 11 | +// This line is incorrect and should be removed |
| 12 | +// ServerSocket ss=new ServerSocket(port); |
| 13 | + |
| 14 | +// Printing the IPv4 address and local port number of the server socket |
| 15 | +System.out.println("Server Socket information: " +ss.getInetAddress() +" " +ss.getLocalPort()); |
| 16 | + |
| 17 | +// Accepting an incoming client connection |
| 18 | +Sockets1 =ss.accept(); |
| 19 | + |
| 20 | +// Printing information about the accepted client connection |
| 21 | +System.out.println("Client Accepted with Information: " +s1.getInetAddress() +" " +s1.getLocalPort()); |
| 22 | + |
| 23 | +// This line won't be printed until a client connects |
| 24 | +System.out.println("Text that won't be printed until client comes in"); |
| 25 | + |
| 26 | +// Creating a DataInputStream object to receive messages from the client |
| 27 | +DataInputStreamdis =newDataInputStream(s1.getInputStream()); |
| 28 | + |
| 29 | +// Reading the message from the client |
| 30 | +Stringstr =dis.readUTF(); |
| 31 | +System.out.println("Message: " +str); |
| 32 | + |
| 33 | +// Creating a DataOutputStream object to send messages to the client |
| 34 | +DataOutputStreamdout =newDataOutputStream(s1.getOutputStream()); |
| 35 | + |
| 36 | +// Sending a message back to the client |
| 37 | +dout.writeUTF("Hello Client"); |
| 38 | +dout.flush(); |
| 39 | + |
| 40 | +// Closing the streams and the socket |
| 41 | +dout.close(); |
| 42 | +dis.close(); |
| 43 | +s1.close(); |
| 44 | +ss.close(); |
| 45 | + }catch (IOExceptione) { |
| 46 | +// Handling any IOException that occurs during socket operations |
| 47 | +System.out.println("An error occurred: " +e); |
| 48 | + } |
| 49 | + } |
| 50 | +} |