-
Notifications
You must be signed in to change notification settings - Fork 3
/
DatagramDemo.java
56 lines (53 loc) · 1.46 KB
/
DatagramDemo.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
44
45
46
47
48
49
50
51
52
53
54
55
56
// Program to demonstrate Datagrams
import java.awt.*;
class DatagramDemo
{
public static int server_port = 998;
public static int client_port = 999;
public static int size = 1024;
public static DatagramSocket ds;
public static byte buffer[] = new byte [size];
public static void TheServer() throws Exception
{
int pos = 0;
while(true)
{
int c = System.in.read();
switch(c)
{
case -1:
System.out.println("Server Quit");
return;
case '\n':
DatagramPacket p1 = new DatagramPacket(buffer,pos,InetAddress.getLocalHost(),client_port);
ds.send(p1);
pos = 0;
break;
default:
buffer[pos++] = (byte)c;
}
}
}
public static void TheClient() throws Exception
{
while(true)
{
DatagramPacket p2 = new DatagramPacket(buffer,buffer.length);
ds.receive(p2);
System.out.println(new String(p2.getData(),0,p2.getLength()));
}
}
public static void main(String args[]) throws Exception
{
if(args.length == 1)
{
ds = new DatagramSocket(server_port);
TheServer();
}
else
{
ds = new DatagramSocket(client_port);
TheClient();
}
}
}