import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.net.ServerSocket; import java.net.Socket; import java.nio.charset.Charset; import java.io.Reader; public class ServeurTCP { private final static char[] hexArray = "0123456789ABCDEF".toCharArray(); public static String bytesToHex(byte[] bytes, int numCharsRead) { char[] hexChars = new char[numCharsRead * 3]; for ( int j = 0; j < numCharsRead; j++ ) { int v = bytes[j] & 0xFF; hexChars[j * 3] = hexArray[v >>> 4]; hexChars[j * 3 + 1] = hexArray[v & 0x0F]; hexChars[j * 3 + 2] = ' '; } return new String(hexChars); } public static Integer tryParse(String text) { try { return Integer.parseInt(text); } catch (NumberFormatException e) { return null; } } public static void main (String[] args) { if (args.length != 1) { System.out.println("utilisation : ServeurTCP port"); return; } Integer port = tryParse(args[0]); if (port == null) { System.out.println("Numéro de port incorrect"); return; } try (ServerSocket server = new ServerSocket (port);) { System.out.println ("en attente de connexion"); while (true) { // Attente du client Socket client = server.accept (); client.setTcpNoDelay(true); try ( InputStream stream = client.getInputStream ()) { System.out.println ("connexion étalie avec " + client.getInetAddress ()); byte[] charArray = new byte[8 * 1024]; while (true) { System.out.println ("Lecture..."); // Lecture du message du client int numCharsRead = stream.read(charArray, 0, charArray.length); if (numCharsRead == -1) { break; } System.out.println (bytesToHex(charArray, numCharsRead)); } } catch (java.net.SocketException e) { System.out.println ("Fin rapide avec " + client.getInetAddress ()); } } } catch (Exception e) { e.printStackTrace(); return; } } }