0

我有一个客户端向服务器发送两个整数:服务器必须对它们求和并再次将结果发送给客户端。我不明白我怎么能做这个总和,因为我没有两个整数,但是:

public class UDPServer {

public static void main(String args[]) throws Exception { 

DatagramSocket serverSocket= new DatagramSocket(1200);



byte[] receiveDataA = new byte[4];
byte[] receiveDataB = new byte[4]; 
byte[] sendDataSum = new byte[4];//  = new byte[1024]; 


while(true) { 

    DatagramPacket receivePacketA = new DatagramPacket(receiveDataA, receiveDataA.length); 
    serverSocket.receive(receivePacketA); 

    DatagramPacket receivePacketB = new DatagramPacket(receiveDataA, receiveDataA.length); 
    serverSocket.receive(receivePacketB);

    String a = new String(receivePacketA.getData(), 0, receivePacketA.getLength()); 
    String b = new String(receivePacketB.getData(), 0, receivePacketB.getLength()); 

    /*here i have to make the sum..how?
    */


    InetAddress IPAddress = receivePacketA.getAddress(); 

    int port = receivePacketA.getPort(); 
    DatagramPacket sendPacketSum = new  DatagramPacket(sendDataSum, sendDataSum.length, IPAddress, port); 

    serverSocket.send(sendPacketSum); 




} 

}

}

4

1 回答 1

0

看一下Integer.parseInt(String)方法

所以:

int aVal = Integer.parseInt(a);
int bVal = Integer.parseInt(b);
int sum = aVal + bVal

然后你可以使用类似ByteBuffer的东西来获取你的字节数组

sendDataSum = ByteBuffer.allocate(4).putInt(sum).array();
于 2013-10-16T17:32:41.847 回答