- package exercise_internet;
- import java.net.DatagramPacket;
- import java.net.DatagramSocket;
- import java.net.InetAddress;
- import java.util.Scanner;
- public class SendAndReceive {
- public static void main(String[] args) {
- // 开启线程用于接收消息
- new Thread() {
- public void run() {
- try {
- receive();
- } catch (Exception e) {
- e.printStackTrace();
- }
- };
- }.start();
- // 主线程发送消息
- try {
- send();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- public static void send() throws Exception {
- System.out.println("send执行");
- DatagramSocket socket = new DatagramSocket();
- Scanner sc = new Scanner(System.in);
- while (true) {
- String line = sc.nextLine();
- DatagramPacket packet = new DatagramPacket(line.getBytes(), line.getBytes().length,
- InetAddress.getByName("127.0.0.1"), 6666);
- socket.send(packet);
- if (line.equals("quit")) {
- break;
- }
- }
- socket.close();
- System.out.println("send结束");
- }
- public static void receive() throws Exception {
- System.out.println("receive执行");
- DatagramSocket socket = new DatagramSocket(6666);
- DatagramPacket packet = new DatagramPacket(new byte[1024], 1024);
- while (true) {
- socket.receive(packet);
- byte[] b = packet.getData();
- int len = packet.getLength();
- String ip = packet.getAddress().getHostAddress();
- int port = packet.getPort();
- String line = new String(b, 0, len);
- if (line.equals("quit")) {
- break;
- }
- System.out.println(ip + ":" + port + ":" + line);
- }
- socket.close();
- System.out.println("receive结束");
- }
- }
复制代码 |
|