-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMiniChat.java
More file actions
38 lines (33 loc) · 1.23 KB
/
MiniChat.java
File metadata and controls
38 lines (33 loc) · 1.23 KB
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
import java.net.*;
import java.util.*;
public class MiniChat {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
System.out.print("Your port: ");
int myPort = sc.nextInt();
System.out.print("Friend's port: ");
int friendPort = sc.nextInt();
sc.nextLine();
DatagramSocket socket = new DatagramSocket(myPort);
InetAddress friend = InetAddress.getByName("localhost");
// Receiver thread
new Thread(() -> {
try {
byte[] buf = new byte[1024];
while (true) {
DatagramPacket p = new DatagramPacket(buf, buf.length);
socket.receive(p);
System.out.println("\nFriend: " + new String(p.getData(), 0, p.getLength()));
System.out.print("You: ");
}
} catch (Exception e) {}
}).start();
// Sender
while (true) {
System.out.print("You: ");
String msg = sc.nextLine();
byte[] data = msg.getBytes();
socket.send(new DatagramPacket(data, data.length, friend, friendPort));
}
}
}