将下面的程序,两台电脑各运行一个,只需要将IP改为接收方的IP,端口号改为你电脑上面空余的端口号(电脑的端口号是0--65535,1024以内是系统的,所以一般建议使用1024以外的端口号)
import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import java.net.UnknownHostException; import java.util.Scanner; public class Chat { public static void main(String[] args) { DatagramSocket sendsocket = null; DatagramSocket receiceSocket = null; try { sendsocket = new DatagramSocket(); receiceSocket = new DatagramSocket(8888,InetAddress.getByName("127.0.0.1")); } catch (SocketException e) { e.printStackTrace(); } catch (UnknownHostException e) { e.printStackTrace(); } new Thread(new Send(sendsocket)).start(); new Thread(new Receive(receiceSocket)).start(); } } class Send implements Runnable{ DatagramSocket socket = null; public Send(DatagramSocket socket) { this.socket = socket; } @Override public void run() { byte[] buf = new byte[1024]; DatagramPacket packet = null; Scanner scanner = new Scanner(System.in); while(true) { String data = scanner.nextLine(); if("over".equalsIgnoreCase(data)) { break; } buf = data.getBytes(); try { //接收方的IP和端口号 packet = new DatagramPacket(buf, buf.length, InetAddress.getByName("127.0.0.1"), 9999); socket.send(packet); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } scanner.close(); } } class Receive implements Runnable{ DatagramSocket socket; public Receive(DatagramSocket socket) { this.socket = socket; } @Override public void run() { while(true) { byte[]buf = new byte[1024]; DatagramPacket packet = new DatagramPacket(buf, buf.length); try { socket.receive(packet); } catch (IOException e) { e.printStackTrace(); break; } String text = new String(packet.getData(), 0, packet.getLength()); String ip = packet.getAddress().getHostAddress(); if("over".equalsIgnoreCase(text)) { break; } System.out.println(ip+" : "+text); } socket.close(); } }
在发送端,要在数据包对象中明确目的地IP及端口
DatagramSocket ds = new DatagramSocket(); byte[] by = “hello,udp”.getBytes(); DatagramPacket dp = new DatagramPacket(by,0,by.length, InetAddress.getByName(“127.0.0.1”),10000); ds.send(dp); ds.close();
在接收端,要指定监听的端口
byte[] by = new byte[1024]; DatagramPacket dp = new DatagramPacket(by,by.length); ds.receive(dp); String str = new String(dp.getData(),0,dp.getLength()); System.out.println(str+"--"+dp.getAddress());
ds.close();
本文地址: http://www.5118.link/article/961705c2b87e9f2dab49.html