如何在java udp数据包中发送字符串数组?我想发送这个数组
String[] name = new String[10];
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:udp");
Statement st=con.createStatement();
String q="select emailfrom from emails where emailto='"+username+"'";
ResultSet rs=st.executeQuery(q);
String user;
int i=0;
String[] name=new String[10];
while(rs.next()){
user=rs.getString("emailftom");
name[i]=user;
byte[] box=name.getBytes();
DatagramPacket p=new DatagramPacket(box,name.length(),request.getAddress(),request.getPort());
aSocket.send(p);
}
}catch(ClassNotFoundException | SQLException ex){
JOptionPane.showMessageDialog(null,ex.getMessage());
}
答案 0 :(得分:1)
您可以对其进行序列化,并发送生成的字节数组。
ByteArrayOutputStream contentStream = new ByteArrayOutputStream()
ObjectOutputStream out = new ObjectOutputStream(contentStream);
out.writeObject(name);
out.flush();
out.close();
byte[] contents = contentStream.toByteArray();
DatagramPacket p=new DatagramPacket(contents,contents.length(),request.getAddress(),request.getPort());
aSocket.send(p);