简体   繁体   English

使用数据报多个数据包的套接字编程Java

[英]Socket Programming java using datagram multiple packets

I am trying to make a client-server program. 我正在尝试制作一个客户端服务器程序。 Where in client i am getting multiple inputs from user and i have to pass it to server. 在客户端,我从用户那里得到多个输入,我必须将其传递给服务器。 Server uses that info and does some calculation and sends back the result. 服务器使用该信息并进行一些计算,然后将结果发送回去。 important parts from Client code: 客户代码中的重要部分:

private byte[] buf = new byte[256];
private byte[] buf2 = new byte[256];
private byte[] buf3 = new byte[256];
while (true) {

Arrays.fill(buf, (byte) 0); 

buf = jTextField1.getText().trim().getBytes();
sendPacket = new DatagramPacket(buf, buf.length, address, 8000);
socket.send(sendPacket);

buf2 = jTextField2.getText().trim().getBytes();
sendPacket = new DatagramPacket(buf2, buf2.length, address, 8000);
socket.send(sendPacket);

buf3 = jTextField3.getText().trim().getBytes();
sendPacket = new DatagramPacket(buf3, buf3.length, address, 8000);
socket.send(sendPacket);

//Get result from Server
socket.receive(recivePacket);
double result  = Double.parseDouble(new String(buf).trim());
System.out.println("Result" +result);

} }

On Server side I am trying to recieve the data(which is not working) 在服务器端,我正在尝试接收数据(不起作用)

   byte[] buf = new byte[256];
   DatagramPacket  recivePacket = new DatagramPacket(buf, buf.length);
   DatagramPacket dgp = new DatagramPacket(buf, buf.length);
    while (true) {
            Arrays.fill(buf, (byte) 0);
            serverSocket.receive(recivePacket);

            System.out.println("host Name is " + 
   recivePacket.getAddress().getHostName() + '\n');

            while (true) {
                serverSocket.receive(dgp);
                System.out.println("String=====" + new String(buf));
            }

Please help me out here. 请帮我在这里。 What is wrong with this code ... I am completely stuck So, its strange that sometimes it works. 这段代码有什么问题...我完全被卡住了,所以奇怪的是,有时它起作用了。 But it gives me value from last buffer. 但这给了我最后一个缓冲的价值。 Other values are lost. 其他值将丢失。 Thanks in advance 提前致谢

So I think each time you recieve something on the server, you need to create a new DatagramPacket/byte[] for that. 因此,我认为每次在服务器上接收到某些内容时,都需要为此创建一个新的DatagramPacket / byte []。 What I do is creating ea new DatagramPacket each time I recieve something like this: 每当我收到这样的消息时,我要做的就是创建一个新的DatagramPacket:

DatagramPacket packet = new DatagramPacket(new byte[max_data_size], max_data_size);
socket.receive(packet);

My max_data_size is normally around 1024 bits . 我的max_data_size is normally around 1024 bits

Then you could read stuff like client, port, length etc: 然后,您可以阅读诸如客户端,端口,长度等内容:

InetAddress address = packet.getAddress();
int port = packet.getPort();
int len = packet.getLength();
byte[] data = packet.getData();

And usually, you should then be able to simply send a new datagramPacket back to the given InetAddress/port. 通常,您应该能够简单地将新的datagramPacket发送回给定的InetAddress /端口。

You want multiple inputs from the user? 您要用户提供多个输入吗? Pack everything in only one package. 将所有东西打包在一个包装中。


private YourClass newInstance(byte[] bytes){
    ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
    ObjectInput in = null;
    YourClass o = null;
    try {
        in = new ObjectInputStream(bis);
        o = (YourClass)in.readObject();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (ClassCastException e){
        e.printStackTrace();
    }finally {
        try {
            if (in != null) {
                in.close();
            }
        } catch (IOException ex) {
            // ignore close exception
        }
    }
    return o;
}

private byte[] toBytes(YourClass object){
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutput out = null;
    byte[] bytes = new byte[1];
    try {
        out = new ObjectOutputStream(bos);

        object.setTimestamp(System.currentTimeMillis());

        out.writeObject(object);
        out.flush();
        bytes = bos.toByteArray();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            bos.close();
        } catch (IOException ex) {
            // ignore close exception
        }
    }
    return bytes;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM