Advertisement
Guest User

Untitled

a guest
Mar 30th, 2017
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.14 KB | None | 0 0
  1. public class ClockSkewServer {
  2. public static void main (String args[]){
  3. try {
  4. ServerSocket s = new ServerSocket(3000);
  5. System.out.println("Server is listening!");
  6. Socket connection = s.accept();
  7. connection.setKeepAlive(true);
  8. BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
  9. PrintWriter pw = new PrintWriter(connection.getOutputStream(), true);
  10. while (true) {
  11.  
  12. String message = br.readLine();
  13. System.out.println(message);
  14. Long receivedTime = ByteUtil.stringToLong(message);
  15. System.out.println(receivedTime);
  16.  
  17.  
  18.  
  19. }
  20. } catch (IOException e) {
  21. // TODO Auto-generated catch block
  22. e.printStackTrace();
  23. }
  24.  
  25.  
  26. }
  27. }
  28.  
  29. public class ClockSkewClient {
  30. public static void main (String args[]) throws UnknownHostException, IOException, InterruptedException{
  31. Socket s1 = new Socket(args[0], 3000);
  32. s1.setKeepAlive(true);
  33. PrintWriter out1 = new PrintWriter(s1.getOutputStream(), true);
  34. long l = new Long("1490917469228");
  35. //System.out.println(l);
  36. while (true){
  37. Thread.sleep(1000);
  38. String message = ByteUtil.longToString(l);
  39. System.out.println("Client message: " + message);
  40. System.out.println(ByteUtil.stringToLong(message));
  41. out1.println(message);
  42. }
  43.  
  44. }
  45. }
  46.  
  47. public class ByteUtil {
  48. private static ByteBuffer longBuffer = ByteBuffer.allocate(Long.BYTES);
  49. private static ByteBuffer shortBuffer = ByteBuffer.allocate(Short.BYTES);
  50. private static ByteBuffer byteBuffer = ByteBuffer.allocate(Byte.BYTES);
  51.  
  52. public static byte[] longToBytes(long x) {
  53. longBuffer.putLong(0, x);
  54. return longBuffer.array();
  55. }
  56.  
  57. public static long bytesToLong(byte[] bytes) {
  58. return ByteBuffer.wrap(bytes).getLong();
  59. }
  60.  
  61.  
  62. public static String longToString (long x) throws UnsupportedEncodingException{
  63. return new String (longToBytes(x), "ISO-8859-1");
  64. }
  65.  
  66. public static long stringToLong (String s) throws UnsupportedEncodingException{
  67. return bytesToLong(s.getBytes("ISO-8859-1"));
  68. }
  69.  
  70.  
  71.  
  72.  
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement