-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathudpBaseServer_2.java
74 lines (62 loc) · 1.96 KB
/
udpBaseServer_2.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// Java program to illustrate Server side
// Implementation using DatagramSocket
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
public class udpBaseServer_2 implements Runnable
{
static NewJDialog dia;
public static void main(String[] args) throws IOException
{
}
public static void init(NewJDialog d) {
dia = d;
}
public static void receiveMessage() throws IOException {
// Step 1 : Create a socket to listen at port 1234
DatagramSocket ds = new DatagramSocket(1234);
byte[] receive = new byte[65535];
DatagramPacket DpReceive = null;
while (true)
{
// Step 2 : create a DatgramPacket to receive the data.
DpReceive = new DatagramPacket(receive, receive.length);
// Step 3 : revieve the data in byte buffer.
ds.receive(DpReceive);
System.out.println("Client:-" + data(receive));
System.out.println("addr = " + DpReceive.getAddress());
String addr = DpReceive.getAddress().toString().substring(1);
NewJDialog.receive(data(receive).toString(), addr, dia);
// Exit the server if the client sends "bye"
// if (data(receive).toString().equals("bye"))
// {
// System.out.println("Client sent bye.....EXITING");
// break;
// }
// Clear the buffer after every message.
receive = new byte[65535];
}
}
// A utility method to convert the byte array
// data into a string representation.
public static StringBuilder data(byte[] a)
{
if (a == null)
return null;
StringBuilder ret = new StringBuilder();
int i = 0;
while (a[i] != 0)
{
ret.append((char) a[i]);
i++;
}
return ret;
}
@Override
public void run() {
try{receiveMessage();}
catch(Exception e){}
}
}