我有一个客户端向服务器发送两个整数:服务器必须将它们相加并再次将结果发送给客户端。我不明白我怎么能这样做,因为我没有两个整数但是:
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);
}
}
}
答案 0 :(得分:0)
这样:
int aVal = Integer.parseInt(a);
int bVal = Integer.parseInt(b);
int sum = aVal + bVal
然后你可以使用类似ByteBuffer的东西来获取你的字节数组
sendDataSum = ByteBuffer.allocate(4).putInt(sum).array();