Java对象在网络上发送

时间:2018-03-16 11:34:47

标签: java

Details d = new Details(5425, "Vosu Mittal/CN");

ByteArrayOutputStream byteoutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectoutputstream = new ObjectOutputStream(byteoutputStream);

objectoutputstream.writeObject(d);     
sendData = byteoutputStream.toByteArray(); 

DatagramPacket sendpacket = new DatagramPacket(sendData, sendData.length, internetAddress, port);
socket.send(sendpacket);

服务器端代码

receivePacket = new DatagramPacket(receiveData, receiveData.length);
socket.receive(receivePacket);
System.out.print("Connected to Server");
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
int packetsize = receivePacket.getLength();
byte[] bytecount = receivePacket.getData();

ByteArrayInputStream byteinputStream = new ByteArrayInputStream(bytecount);
ObjectInputStream objectinputStream = new ObjectInputStream(byteinputStream);

Details d = (Details)objectinputStream.readObject();
String data = new String(d.toString());

System.out.println("\t"+ data+ "\tIP Address is = "+ IPAddress+ "\tPort Address is ="+ port+ "\tByte Count is = "+ packetsize );
String reply = "Thank you for the message";

我的类定义为Follows with Serializable Interface

int id;
String name;

private void showDetails(){
    System.out.println("Id:"+id);
    System.out.println("Name:"+name);
}

但是,我无法在客户端获取它们,如果需要,请纠正代码?

0 个答案:

没有答案