Skip to content

Commit d28c751

Browse files
authored
Added new programme
1 parent e41a187 commit d28c751

File tree

1 file changed

+60
-0
lines changed
  • UDP_Server_And_Client_Application/Programed_In_the_teacher's_way

1 file changed

+60
-0
lines changed
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
import java.io.IOException;
2+
import java.net.DatagramPacket;
3+
import java.net.DatagramSocket;
4+
import java.net.InetAddress;
5+
import java.net.UnknownHostException;
6+
import java.util.Scanner;
7+
8+
public class ClientDatagram {
9+
10+
private static InetAddress host;
11+
private static final int PORT = 2082;
12+
private static DatagramSocket datagramSocket;
13+
private static DatagramPacket inPacket, outPacket;
14+
private static byte[] buffer;
15+
16+
public static void main(String[] args) {
17+
try {
18+
host = InetAddress.getLocalHost();
19+
} catch (UnknownHostException unknownHostException) {
20+
System.out.println("ERROR : " + unknownHostException.getMessage());
21+
System.exit(1);
22+
}
23+
accessServer();
24+
}
25+
26+
private static void accessServer() {
27+
try {
28+
datagramSocket = new DatagramSocket(); //STEP 1
29+
Scanner userEntry = new Scanner(System.in);
30+
String message = "", response = "";
31+
do {
32+
System.out.println("Enter Message : ");
33+
message = userEntry.nextLine();
34+
if (!message.equals("***CLOSE***")) {
35+
outPacket = new DatagramPacket(message.getBytes(), message.l
36+
ength(), host, PORT); //STEP 2
37+
datagramSocket.send(outPacket); //STEP 3
38+
buffer = new byte[256]; //STEP 5
39+
inPacket = new DatagramPacket(buffer, buffer.length); //STEP
40+
5
41+
datagramSocket.receive(inPacket); //STEP 6
42+
response = new String(inPacket.getData(), 0, inPacket.getLen
43+
gth()); //STEP 7
44+
System.out.println("\n SERVER RESPONSE > " + response );
45+
46+
}
47+
48+
} while (!message.equals("***CLOSE***"));
49+
} catch (IOException ioException) {
50+
ioException.printStackTrace();
51+
System.out.println("ERROR" + ioException.getMessage());
52+
53+
}finally {
54+
System.out.println("\n * Closing connection ... *");
55+
datagramSocket.close(); // STEP 8
56+
57+
}
58+
}
59+
60+
}

0 commit comments

Comments
 (0)