案例实现的功能:键盘录入一句话,通过udp发送给对方
代码如下:
- <p>import java.io.IOException;
- import java.net.DatagramPacket;
- import java.net.DatagramSocket;</p><p>public class ReiceiveDemo {
- public static void main(String[] args) throws IOException {
- DatagramSocket ds = new DatagramSocket(10087);
- byte[] bys = new byte[1024];
- DatagramPacket dp = new DatagramPacket(bys, bys.length);
- ds.receive(dp);
- String s = new String(dp.getData(), 0, dp.getLength());
- System.out.println("接收到的数据是:" + s);
- }
- }
- </p><p> </p><p>import java.io.IOException;
- import java.net.DatagramPacket;
- import java.net.DatagramSocket;
- import java.net.InetAddress;
- import java.util.Scanner;</p><p>public class SendDemo {
- public static void main(String[] args) throws IOException {
- DatagramSocket ds = new DatagramSocket();
- Scanner sc = new Scanner(System.in);
- System.out.println("请输入您要发送的数据:");
- String s = sc.nextLine();
- byte[] bys = s.getBytes();
- DatagramPacket dp = new DatagramPacket(bys, bys.length,
- InetAddress.getByName("lisa"), 10087);
- ds.send(dp);
- ds.close();
- }
- }
- </p><p> </p>
复制代码
|
|