日期:2014-05-20  浏览次数:20736 次

有关于java socket发送与接收的问题
RT,我想要连续发送10个对象到服务器,代码如下
//发送代码
Java code

for (int i = 0; i < 10; i++)
        {
            ping = new Ping();
            
            
            sendMessage(InetAddress.getByName("localhost"), Integer.parseInt(port),
                    ping);




                }

public void sendMessage(InetAddress receiveHost, int receivePort,
            Ping message) throws IOException
    {
        try
        {
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            ObjectOutputStream oout = new ObjectOutputStream(bout);

            oout.writeObject(message); // 序列化对象
            oout.flush();

            byte[] sendBuff = bout.toByteArray(); // 转化为字节数组

            DatagramPacket datagram = new DatagramPacket(sendBuff,
                    sendBuff.length, receiveHost, receivePort);

            DatagramSocket socket = new DatagramSocket();

            socket.send(datagram); // 通过DatagramPacket发送对象
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
    }





//接收代码
Java code

Ping p = receiveMessage();


public Ping receiveMessage() throws Exception
    {
        byte[] receiveBuff = new byte[1024];
        DatagramPacket datagram = new DatagramPacket(receiveBuff, 1024);
        DatagramSocket socket = new DatagramSocket(Integer.parseInt(port));
        socket.receive(datagram);

        Ping message = new Ping();

        try
        {
            ByteArrayInputStream bint = new ByteArrayInputStream(receiveBuff);
            ObjectInputStream oint = new ObjectInputStream(bint);
            message = (Ping) oint.readObject(); // 反序列化,恢复对象
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }

        return message;
    }




现在的问题是,我只能接收到第一个socket,请各位大虾指教

------解决方案--------------------
不错,
------解决方案--------------------
既然你搞定了,那我接个分得了。