Skip to content

Instantly share code, notes, and snippets.

@geo-stanciu
Created March 9, 2016 11:23
Show Gist options
  • Save geo-stanciu/aded652c571ae91a4191 to your computer and use it in GitHub Desktop.
Save geo-stanciu/aded652c571ae91a4191 to your computer and use it in GitHub Desktop.
java - send and receive data from sockets
package org.geo.utils;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.nio.charset.StandardCharsets;
public class SocketUtils {
public SocketUtils() {
super();
}
@SuppressWarnings("oracle.jdeveloper.java.nested-assignment")
public static String getMessage(DataInputStream in) throws Exception {
byte[] buff = new byte[10];
int count = 0;
while (count < 10)
buff[count++] = in.readByte();
String slen = new String(buff, StandardCharsets.US_ASCII);
int len = Integer.valueOf(slen);
count = 0;
int offset = 0;
byte[] bytes = new byte[len];
while ((count = in.read(bytes, offset, len - offset)) != -1) {
offset += count;
if (offset >= len) {
break;
}
}
String line = new String(bytes, 0, offset, "UTF-8");
return line;
}
public static void sendMessage(DataOutputStream out, String msg) throws Exception {
String slen = String.format("%10d", msg.length()).replace(' ', '0');
String message = slen + msg;
out.write(message.getBytes(StandardCharsets.UTF_8));
out.flush();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment