通过DatagramSocket类来实现。此类表示用来发送和接收数据报包的套接字。
发送端代码如下:
2 3 import java.io.IOException; 4 import java.net.*; 5 import java.util.Scanner; 6 7 public class Send implements Runnable{ 8 @Override 9 public void run() { 10 //创建一个发送消息的套接字 11 DatagramSocket sendSocket = null; 12 try { 13 sendSocket = new DatagramSocket(); 14 } catch (SocketException e) { 15 e.printStackTrace(); 16 } 17 while (true) { 18 try { 19 System.out.println("发送端发送消息"); 20 Scanner sc = new Scanner(System.in); 21 String msg = sc.next(); 22 23 byte [] bytes = msg.getBytes();//发送的内容转化为字节数组 24 InetAddress ip = InetAddress.getByName("192.168.31.169");//接受内容的Ip地址 25 26 //创建要发送的数据包,然后用套接字发送 27 DatagramPacket datagramPacket = new DatagramPacket(bytes,bytes.length,ip,8080); 28 //用套接字发送数据包 29 sendSocket.send(datagramPacket); 30 31 } catch (SocketException e) { 32 e.printStackTrace(); 33 } catch (UnknownHostException e) { 34 e.printStackTrace(); 35 } catch (IOException e) { 36 e.printStackTrace(); 37 } 38 } 39 } 40 41 public static void main(String[] args){ 42 Send s = new Send(); 43 Thread thread = new Thread(s); 44 thread.start(); 45 } 46 }
接收端代码如下:
2 3 import java.io.IOException; 4 import java.net.DatagramPacket; 5 import java.net.DatagramSocket; 6 import java.net.InetAddress; 7 import java.net.SocketException; 8 9 public class Receive implements Runnable { 10 @Override 11 public void run() { 12 System.out.println("接收端"); 13 //创建接受消息的套接字 14 DatagramSocket receviceSocket = null; 15 try { 16 receviceSocket = new DatagramSocket(8080); 17 } catch (SocketException e) { 18 e.printStackTrace(); 19 } 20 while (true) { 21 try { 22 byte [] bytes = new byte[2048]; 23 //创建一个数据包来接受消息 24 DatagramPacket datagramPacket = new DatagramPacket(bytes,bytes.length); 25 //用套接字接受数据包 26 receviceSocket.receive(datagramPacket); 27 //得到发送端的ip地址 28 InetAddress ip = datagramPacket.getAddress(); 29 //将接受到的消息转换为字符串 30 String rec = new String(datagramPacket.getData()) ; 31 System.out.println(ip.getHostAddress()+"发送的消息为:"+rec); 32 33 } catch (SocketException e) { 34 e.printStackTrace(); 35 } catch (IOException e) { 36 e.printStackTrace(); 37 } 38 } 39 } 40 41 public static void main(String[] args) { 42 Receive r = new Receive(); 43 Thread thread = new Thread(r); 44 thread.start(); 45 } 46 }
因为要一直接受消息和发送消息,故用了while循环。
注意事项:发送端的端口要和接收端的端口保持一致。
这里我接受消息的ip地址设置为自己的ip地址来演示实际效果。
时间: 2024-10-07 09:44:01