Skip to content

Commit a17cb70

Browse files
authored
Create Server.java
1 parent 7dc10d3 commit a17cb70

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

Server.java

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
import java.io.*;
2+
import java.net.*;
3+
4+
public class Server {
5+
public static void main(String[] args) {
6+
try {
7+
// Creating a ServerSocket object to listen on a specific port
8+
ServerSocket ss = new ServerSocket(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+
Socket s1 = 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+
DataInputStream dis = new DataInputStream(s1.getInputStream());
28+
29+
// Reading the message from the client
30+
String str = dis.readUTF();
31+
System.out.println("Message: " + str);
32+
33+
// Creating a DataOutputStream object to send messages to the client
34+
DataOutputStream dout = new DataOutputStream(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 (IOException e) {
46+
// Handling any IOException that occurs during socket operations
47+
System.out.println("An error occurred: " + e);
48+
}
49+
}
50+
}

0 commit comments

Comments
 (0)