[英]How to send Vector over UDP conection in JAVA
I am trying to send vector object from UDP server to UDP client in Java. 我正在尝试将向量对象从UDP服务器发送到Java中的UDP客户端。
Sending and Receiving string as an object after serializing has been achieved , but I am unable to send or receive vectors. 实现串行化之后,将字符串作为对象发送和接收,但是我无法发送或接收向量。 Below is server ide code.
下面是服务器端代码。
public class UDPReceive {
public UDPReceive() throws IOException {
try {
int port = Integer.parseInt("1233");
int allReceived=0;
String[] custData=new String[3];
DatagramSocket dsocket = new DatagramSocket(port);
byte[] buffer = new byte[2048];
for(;;) {
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
dsocket.receive(packet);
String msg = new String(buffer, 0, packet.getLength());
String msg2 = new String(packet.getData());
custData[allReceived]=msg;
allReceived++;
if(allReceived == 3){
System.out.println("All Data Received");
for(int i=0;i<3;i++){
System.out.println(custData[i]);
}
Vector rawData=getTransactions(custData[0],custData[1],custData[2]);
System.out.println("Vectot size "+ rawData.size());
byte[] sendData = new byte[1024];
sendData=(object[])rawData.toArray();
allReceived=0;
}/*if ends here */
}
}
catch (Exception e) {
System.err.println(e);
}
}
Here I want to send back "rawData" variable to client and receive it, and covert it to vector in client side. 在这里,我想将“ rawData”变量发送回客户端并接收它,然后在客户端将其转换为向量。 I tried using byte[] as well, but it didn't work
我也尝试使用byte [],但是没有用
I suggest you serialize the Vector as an ObjectOutputStream and use ObjectInputStream to get the original Vector. 我建议您将Vector序列化为ObjectOutputStream并使用ObjectInputStream获得原始Vector。
public static byte[] objectToBytes(Object o) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(o);
oos.close();
return baos.toByteArray();
}
to reverse 扭转
public static <T> T bytesToObject(byte[] bytes) throws IOException, ClassNotFoundException {
return (T) new ObjectInputStream(new ByteArrayInputStream(bytes)).readObject();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.