JAVA—UDP网络通信
客户端:
public class UDPClient {
public static void main(String[] args) throws Exception{
String data = "英雄赤胆一腔热血撒不尽";
DatagramSocket ds = new DatagramSocket();
byte[] buf = data.getBytes();
InetAddress address = InetAddress.getByName("127.0.0.1");
DatagramPacket dp = new DatagramPacket(buf,buf.length,address,17787);
ds.send(dp);
buf = new byte[1024];
dp = new DatagramPacket(buf,buf.length);
ds.receive(dp);
byte[] bytes = dp.getData();
Object o = byteArrayToObject(bytes);
System.out.println(o.toString());
}
public static Object byteArrayToObject(byte[] buf)throws Exception{
ByteArrayInputStream bais = new ByteArrayInputStream(buf);
ObjectInputStream ois =new ObjectInputStream(bais);
Object o = ois.readObject();
ois.close();
return o;
}
}
服务端:
public class UDPServer {
public static void main(String[] args) throws Exception{
while (true){
DatagramSocket ds = new DatagramSocket(17787);
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf,buf.length);
ds.receive(dp);
byte[] data = dp.getData();
String str = new String(data,0,dp.getLength());
System.out.println("接收到的数据: " + str);
User user = new User("赵丽颖","123456");
data = objectToByteArray(user);
dp = new DatagramPacket(data,data.length,dp.getAddress(),dp.getPort());
ds.send(dp);
ds.close();
}
}
public static byte[] objectToByteArray(Object o) throws Exception{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(o);
oos.close();
return baos.toByteArray();
}
}
class User implements Serializable{
private String name;
private String pwd;
public User(String name, String pwd) {
this.name = name;
this.pwd = pwd;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", pwd='" + pwd + '\'' +
'}';
}
}