// 服务器端
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class UDPServer {
public static void main(String[] args) {
try {
System.out.println("server start...");
DatagramSocket ds = new DatagramSocket(6666);
// 定义通道中字符数组大小
byte [] buff = new byte [1024];
DatagramPacket dp = new DatagramPacket(buff, buff.length);
ds.receive(dp);
// 字节数组读取流
ByteArrayInputStream bis = new ByteArrayInputStream(buff);
// 字节数组包装类
DataInputStream dis = new DataInputStream(bis);
// dis.readLong 读出的packet中的数据
System.out.println(dis.readLong());
ds.close();
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//客户端
package com.lanou3g.zte;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.util.Scanner;
public class UDPClient {
public static void main(String[] args) {
try {
DatagramSocket dSocket = new DatagramSocket(7777);
long l = 1000L;
// 字节流通道
ByteArrayOutputStream bo = new ByteArrayOutputStream();
//字节流包装类
DataOutputStream dos = new DataOutputStream(bo);
// 把long l 写入字节数组
dos.writeLong(l);
// bo.toByteArray() 创建一个新分配的字节数组。 其大小是此输出流的当前大小,缓冲区的有效内容已被复制到其中
byte [] buff = bo.toByteArray();
DatagramPacket dPacket = new DatagramPacket(buff, buff.length, new InetSocketAddress("192.168.90.194", 6666));
dSocket.send(dPacket);
dSocket.close();
dos.close();
bo.close();
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}