-
Notifications
You must be signed in to change notification settings - Fork 0
/
UDPSocketClient.java
43 lines (40 loc) · 1.55 KB
/
UDPSocketClient.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.*;
public class UDPSocketClient {
DatagramSocket Socket;
public UDPSocketClient() {}
public void createAndListenSocket() {
try {
Socket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName("localhost");
byte[] incomingData = new byte[1024];
Student student = new Student(1, "Bijoy", "Kerala");
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ObjectOutputStream os = new ObjectOutputStream(outputStream);
os.writeObject(student);
byte[] data = outputStream.toByteArray();
DatagramPacket sendPacket = new DatagramPacket(data, data.length, IPAddress, 9876);
Socket.send(sendPacket);
System.out.println("Message sent from client");
DatagramPacket incomingPacket = new DatagramPacket(incomingData, incomingData.length);
Socket.receive(incomingPacket);
String response = new String(incomingPacket.getData());
System.out.println("Response from server:" + response);
Thread.sleep(2000);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
UDPSocketClient client = new UDPSocketClient();
client.createAndListenSocket();
}
}