关于UDP:将数据及源和目的封装成数据包中,不需要建立连接;每个数据报的大小在限制在64k内;因无连接,是不可靠协议;不需要建立连接,速度快
使用udp协议主要涉及到两个类:DatagramSocket,DatagramPacket
DatagramSocket: 用于建立一个数据包的出口或入口,构造方法中有IP的都是用于接收方的
DatagramPacket: 用于包装数据,构造方法中有IP的都是用于发送方的
可以将其比作发送包裹,DatagramSocket就是快递公司,选择哪一个快递公司并不会影响包裹的发送;而DatagramPacket则是你的包裹,上面必须写明地址(IP)和门牌号(port:端口号).
下面的程序,两台电脑各运行一个,只需要将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();
}
}
-------------------------------#以下是补充内容,2018-10-16 #----------------------------------------
在发送端,要在数据包对象中明确目的地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();
在接收端,要指定监听的端口
DatagramSocket ds = new DatagramSocket(10000);
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();