Java Socket Send float values or group of float values
Server:
class SampleServer {
public static void main(String args[]) throws Exception {
ServerSocket serverSocket = new ServerSocket(9080);
Socket socket = serverSocket.accept();
DataInputStream dataInSt = new DataInputStream(socket.getInputStream());
String string = "";
while (!string.equals("stop")) {
FloatBuffer buf = FloatBuffer.allocate(4);
byte[] bs = new byte[buf.capacity()*4];
dataInSt.read(bs);
FloatBuffer fb = ByteBuffer.wrap(bs).asFloatBuffer();
for(int i=0;i<fb.capacity();i++) {
System.out.println("Message: " + fb.get(i));
}
Thread.sleep(1000);
}
dataInSt.close();
socket.close();
serverSocket.close();
}
}
Client:
class SampleClient {
public static void main(String args[]) throws Exception {
Socket socket = new Socket("localhost", 9080);
DataOutputStream dataOuSt = new DataOutputStream(
socket.getOutputStream());
String string = "";
while (!string.equals("stop")) {
FloatBuffer input = FloatBuffer.allocate(4);
input.put(5.5f);
input.put(1.5f);
input.put(2.5f);
input.put(3.5f);
float[] f = input.array();
byte[] output = float2Byte(f);
dataOuSt.write(output);
dataOuSt.flush();
}
dataOuSt.close();
socket.close();
}
public static final byte[] float2Byte(float[] inData) {
int j = 0;
int length = inData.length;
byte[] outData = new byte[length * 4];
for (int i = 0; i < length; i++) {
int d = Float.floatToIntBits(inData[i]);
outData[j++] = (byte) (d >>> 24);
outData[j++] = (byte) (d >>> 16);
outData[j++] = (byte) (d >>> 8);
outData[j++] = (byte) (d >>> 0);
}
return outData;
}
}
Leave your feedback's.........................
No comments:
Post a Comment