tousif ahmed
tousif ahmed

Reputation: 11

how to send array of String in java datagrampacket?

How can I send an array of Strings in a java udp packet? I want to send this array 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());
    }

Upvotes: 0

Views: 821

Answers (1)

Dimitris Fousteris
Dimitris Fousteris

Reputation: 1111

You can serialize it, and send the resulting byte array.

    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);

Upvotes: 1

Related Questions