Created
March 9, 2016 11:23
-
-
Save geo-stanciu/aded652c571ae91a4191 to your computer and use it in GitHub Desktop.
java - send and receive data from sockets
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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