一.UDP通信的基本模式
发送数据包:
(1)DatagramSocket类创建套接字 : new DatagramSocket();不需要指定端口号码, UDP协议,系统自己选择一个端口发送出去;
(2)DatagramPacket类创建数据包 :new DatagramPacket(byte[] buf ,int offset , int length ,InetAddress address , int port );
(3)使用 DatagramSocket 的send 函数发送出去: socket.sent(DatagramPacket p) .
接收数据包:
(1)DatagramSocket类创建套接字 :new DatagramSocket(int port ) ; 指定端口号;
(2)DatagramPacket 类创建数据包:new DatagramPacket(byte[] buf , int length);
(3)DatagramSocket 的receive(DatagramPacket p) 来接受数据包;
注: DatagramSocket 的receive(p) 函数在没有数据接受的时候是堵塞的,如果没有数据receive没有堵塞 ,那可能是端口号被占用了。
服务器端
package Udp;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
public class EasyServer {
private static final int port = 8998;
private byte [] buf;
private DatagramSocket socket ;
private DatagramPacket packet ;
EasyServer(){
try {
socket = new DatagramSocket(port);
buf = new byte[1024];
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void getMsg(){
String s = "";
packet = new DatagramPacket(buf, buf.length);
while(true){
try {
socket.receive(packet);
s = new String (buf);
System.out.println("client sent to me :"+ s);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main (String args []){
new EasyServer().getMsg();
}
}
客户端
package Udp;
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 EasyClient {
private static final int port = 8998;
private DatagramSocket socket ;
private DatagramPacket packet ;
byte buf [];
EasyClient(){
try {
socket = new DatagramSocket();
buf = new byte[1024];
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@SuppressWarnings("resource")
public void senMsg(){
Scanner scan = new Scanner(System.in);
try {
InetAddress add = InetAddress.getLocalHost();
while (true){
String s = scan.nextLine();
buf = s.getBytes();
packet = new DatagramPacket(buf, 0, buf.length, add, port);
try {
socket.send(packet);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main (String args[]){
new EasyClient().senMsg();
}
}