用UDP网络编程做简易聊天工具

这个聊天工具仅供自娱自乐

聊天窗口一

public static void main(String[] args) throws IOException {
		System.out.println("请发送消息");
		while (true) {
			DatagramSocket ds = new DatagramSocket(8888);
			Scanner sc = new Scanner(System.in);
			
			String str = sc.nextLine();
			byte[] b = str.getBytes();
			InetAddress address = InetAddress.getLocalHost();
			int port = 6666;
			DatagramPacket dp = new DatagramPacket(b, 0, b.length, address,
					port);
			ds.send(dp);
			
			byte[] buf = new byte[1024];
			DatagramPacket dp1 = new DatagramPacket(buf, 0, buf.length);
			ds.receive(dp1);
			System.out.println(new String(buf));
			ds.close();
		}
	}

聊天窗口二

public static void main(String[] args) throws IOException {
		while (true) {
			DatagramSocket ds = new DatagramSocket(6666);
			byte[] buf = new byte[1024];
			DatagramPacket dp = new DatagramPacket(buf, 0, buf.length);
			ds.receive(dp);
			System.out.println(new String(buf));
			Scanner sc = new Scanner(System.in);
			
			String str = sc.nextLine();
			byte[] b = str.getBytes();
			InetAddress address = InetAddress.getLocalHost();
			int port = 8888;
			DatagramPacket dp1 = new DatagramPacket(b, 0, b.length, address,
					port);
			ds.send(dp1);
			ds.close();
		}
	}

效果图

用UDP网络编程做简易聊天工具_第1张图片

你可能感兴趣的:(java基础语法)