Socket envoi pas tous les data
Bonjour à tous,
alors j'ai fait pour commencer un socket serveur et client,
le client envoi "e04fd020ea3a6910a2d808002b30309d"
mais le serveur reçois qu'une partie à savoir "4f203a10d80309d".
Dois-je mettre un Thread.sleep() quelque part ? :?
Serveur :
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
|
public class SocketServer extends Thread
{
private ServerSocket serverSocket;
private String bitS = "";
public SocketServer(int port) throws IOException
{
serverSocket = new ServerSocket(port);
serverSocket.setSoTimeout(1000000);
}
@Override
public void run()
{
while(true)
{
try
{
System.out.println("écoute sur le port : " +
serverSocket.getLocalPort() + "...");
try (Socket server = serverSocket.accept()) {
System.out.println("connecté à : " + server.getRemoteSocketAddress());
DataInputStream in = new DataInputStream(server.getInputStream());
//System.out.println(in.readUTF());
while(in.readBoolean())
{
bitS = bitS + Integer.toHexString(in.read());
}
System.out.println(bitS);
DataOutputStream out = new DataOutputStream(server.getOutputStream());
out.writeUTF("connexion réussie " + server.getLocalSocketAddress() + "\nfin");
in.close();
out.close();
}
}catch(SocketTimeoutException s)
{
System.out.println("temps écoulé");
break;
}catch(IOException e)
{
System.out.println("erreur : " + e);
break;
}
}
}
public static void main(String [] args)
{
int port = 12654;
try
{
Thread t = new SocketServer(port);
t.start();
}catch(IOException e)
{
}
}
} |
Client :
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
|
public class Client2 {
public static byte[] hexStringToByte(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i+1), 16));
}
return data;
}
public static void main(String[] args) throws InterruptedException {
String serverName = "localhost";
int port = 12654;
byte[] b = hexStringToByte("e04fd020ea3a6910a2d808002b30309d");
try
{
System.out.println("Connexion à " + serverName + " sur le port " + port);
try (Socket client = new Socket(serverName, port)) {
System.out.println("connecté à : " + client.getRemoteSocketAddress());
OutputStream outToServer = client.getOutputStream();
try (DataOutputStream out = new DataOutputStream(outToServer)) {
out.write(b);
out.writeUTF("Salut c'est : " + client.getLocalSocketAddress()+ " le 2e client "
+ "\n attention j'envoi en byte ^^");
InputStream inFromServer = client.getInputStream();
try (DataInputStream in = new DataInputStream(inFromServer)) {
System.out.println("Réponse du serveur : " + in.readUTF());
}
}
}
}catch(IOException e)
{
System.out.println("erreur : " + e);
}
}
} |