#IDEA 小技巧

  • cmd + shift + enter代码自动补全。
  • cmd + p参数提示。
  • psvm等价于public static void main(String[] args) {}
  • sout等价于System.out.println();
  • cmd + alt + t可以在代码块外面添加:
    1. if
    2. if / else
    3. while
    4. do / while
    5. for
    6. try / catch
  • alt + enternew MyClass();后会自动填充为MyClass myclass = new MyClass();
  • cmd + alt + shift + l格式化代码。

#UDP 发送端

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
package xyz.onns.chat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;

public class MySender implements Runnable {
DatagramSocket socket = null;
BufferedReader reader = null;
private String toIP;
private int fromPort;
private int toPort;

public MySender(String toIP, int fromPort, int toPort) {
this.toIP = toIP;
this.fromPort = fromPort;
this.toPort = toPort;
try {
socket = new DatagramSocket(fromPort);
reader = new BufferedReader(new InputStreamReader(System.in));
} catch (SocketException e) {
e.printStackTrace();
}
}

@Override
public void run() {
while (true) {
try {
String data = reader.readLine();
byte[] buffer = data.getBytes();
DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length, new InetSocketAddress(toIP, toPort));
socket.send(packet);
if (data.trim().equals("bye")) {
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
socket.close();
}
}

#UDP 接收端

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
package xyz.onns.chat;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class MyReceiver implements Runnable {
DatagramSocket socket = null;
private int port;
private String from;

public MyReceiver(int port, String from) {
this.port = port;
this.from = from;
try {
socket = new DatagramSocket(port);
} catch (SocketException e) {
e.printStackTrace();
}
}


@Override
public void run() {
while (true) {
try {
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet);
byte[] data = packet.getData();
String message = new String(data, 0, data.length);
System.out.println(from + " : " + message);
if (message.trim().equals("bye")) {
break;
}

} catch (Exception e) {
e.printStackTrace();
}
}
socket.close();
}
}

#测试类

1
2
3
4
5
6
7
8
package xyz.onns.chat;

public class TalkStudent {
public static void main(String[] args) {
new Thread(new MySender("localhost",7777,9999)).start();
new Thread(new MyReceiver(8888,"teacher")).start();
}
}
1
2
3
4
5
6
7
8
package xyz.onns.chat;

public class TalkTeacher {
public static void main(String[] args) {
new Thread(new MySender("localhost",5555,8888)).start();
new Thread(new TalkReceiver(9999,"student")).start();
}
}