2017-10-05 6 views
-1

J'essaie d'envoyer des octets et de les recevoir via ma connexion socket, mais ils ne le font pas non plus. Je ne suis pas sûr si c'est un problème à faire avec la façon dont j'envoie les octets et les chaînes ou parce que je ne sais pas comment lire à partir du serveur et du client.Mon socket n'envoie pas ou ne reçoit pas bytearrays

client

public class Client implements Runnable { 

private Socket socket; 
private ByteArrayOutputStream buffer; 
private OutputStream output; 
private Stage stage; 

public Client() { 
    try { 
     this.socket = new Socket("localhost", 1337); 
     this.socket.setTcpNoDelay(true); 
     this.socket.setKeepAlive(true); 
     this.output = this.socket.getOutputStream(); 
     InputStream input = this.socket.getInputStream(); 
     this.buffer = new ByteArrayOutputStream(); 
     Thread connection = new Thread(this); 
     connection.start(); 
     this.sendPacket(0, ByteBuffer.allocate(16 + "TEST".length()).putInt("TEST".length()).put("TEST".getBytes(Constants.UTF8)).array()); 
     System.out.println("[CLIENT] Successfully connected to server."); 
    } catch (Exception e) { 
     IOUtils.output("[CLIENT] Error when connecting to server."); 
     System.exit(1337); 
    } 
} 

@Override 
public void run() { 
    try { 
     while (this.connected()) { 
      byte[] bytes = this.buffer.toByteArray(); 
      Constants.received += bytes.length; 
      if (bytes.length < 8) return; 
      ByteBuffer cbuf = ByteBuffer.wrap(bytes); 
      int size = cbuf.getInt(); 
      int id = cbuf.getInt(); 
      if (bytes.length < size + 8) continue; 
      byte[] data = Arrays.copyOfRange(bytes, 8, 8 + size); 
      this.processPacket(id, data); 
      this.buffer.close(); 
      (this.buffer = new ByteArrayOutputStream()).write(bytes, 8 + size, bytes.length - 8 - size); 
     } 
     System.out.println("[CLIENT] Disconnected from server."); 
     System.exit(1337); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 

private void processPacket(int id, byte[] bytes) { 
    ByteBuffer data = ByteBuffer.wrap(bytes); 
    if (id == 0) { 
    System.out.println("Received packet from server with id 0"); 
    } else if (id == 1) { 
    System.out.println("Received packet from server with id 1"); 
    } 
} 

private void sendPacket(int id, byte[] data) { 
    try { 
     ByteBuffer bytebuffer = ByteBuffer.allocate(8 + data.length); 
     bytebuffer.putInt(data.length); 
     bytebuffer.putInt(id); 
     bytebuffer.put(data); 
     byte[] bytes = bytebuffer.array(); 
     Constants.sent += bytes.length; 
     this.output.write(bytes); 
     this.output.flush(); 
    } catch (IOException e) { 
     try { 
      socket.close(); 
     } catch (IOException io) { 
      IOUtils.output("[CLIENT] Error with client."); 
      System.exit(1337); 
     } 
    } 
} 

private boolean connected() { 
    return this.socket.isConnected() && !this.socket.isInputShutdown() && !this.socket.isOutputShutdown() && !this.socket.isClosed(); 
} 


} 

ServerHandler

public class Handler implements Runnable { 

private Socket socket; 
private ByteArrayOutputStream buffer; 
private OutputStream output; 

public Handler(Socket socket) { 
    this.socket = socket; 
    try { 
     this.output = this.socket.getOutputStream(); 
     InputStream input = this.socket.getInputStream(); 
     this.buffer = new ByteArrayOutputStream(); 
     Thread connection = new Thread(this); 
     connection.start(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 

@Override 
public void run() { 
    try { 
     IOUtils.output("[HANDLER] Connection from " + socket.getInetAddress()); 
     while (connected()) { 
      byte[] bytes = this.buffer.toByteArray(); 
      if (bytes.length < 8) return; 
      ByteBuffer buffer = ByteBuffer.wrap(bytes); 
      int size = buffer.getInt(); 
      int id = buffer.getInt(); 
      if (bytes.length < size + 8) continue; 
      byte[] data = Arrays.copyOfRange(bytes, 8, 8 + size); 
      this.processPacket(id, data); 
      this.buffer.close(); 
      (this.buffer = new ByteArrayOutputStream()).write(bytes, 8 + size, bytes.length - 8 - size); 
     } 
     IOUtils.output("[HANDLER] Client ended connection - " + socket.getInetAddress()); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 

private void sendPacket(int id, byte[] data) { 
    try { 
     ByteBuffer bytebuffer = ByteBuffer.allocate(8 + data.length); 
     bytebuffer.putInt(data.length); 
     bytebuffer.putInt(id); 
     bytebuffer.put(data); 
     byte[] bytes = bytebuffer.array(); 
     this.output.write(bytes); 
     this.output.flush(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 

private void processPacket(int id, byte[] bytes) { 
    ByteBuffer data = ByteBuffer.wrap(bytes); 
    if (id == 0) { 
     IOUtils.output("Recieved packet with id 0"); 
    } else if (id == 1) { 
     //TODO: authenticate user. 
    } 
} 

private boolean connected() { 
    return this.socket.isConnected() && !this.socket.isInputShutdown() && !this.socket.isOutputShutdown() && !this.socket.isClosed(); 
} 

} 

serveur

public class Server implements Runnable { 

private int port; 
private ServerSocket sock; 

public Server(int port) { 
    this.port = port; 
    launch(); 
} 

private void launch() { 
    this.run(); 
} 

@Override 
public void run() { 
    try { 
     sock = new ServerSocket(port); 
     System.out.println("[SERVER] Server started"); 
     while(!sock.isClosed()) { 
      new Handler(sock.accept()); 
     } 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 

} 

Je pense que ce problème pourrait être avec ByteArrayOutputStream. Je voulais utiliser ByteBuffer parce que j'ai entendu dire que c'était beaucoup plus rapide que les flux DataInput et de sortie normaux.

Répondre

1

Vous n'appelez jamais Socket # dans votre méthode d'exécution ... Si vous ne lisez rien, vous n'avez rien à faire dans votre boucle, même lorsque vous êtes connecté!

Jetez un oeil à ce tutoriel sur les sockets:

https://docs.oracle.com/javase/tutorial/networking/sockets/readingWriting.html

+0

Je comprends ce que vous voulez dire, mais que puis-je lire? J'envoie des octets non entiers. L'entrée inputstream.read renvoie un int. –

+0

@OmarAhmed jeter un oeil à la description de la méthode, read() lit byte et utilise int pour le représenter, aussi vous avez la méthode read (byte []) qui vous renvoie le nombre octet lu – user902383

+0

@ user902383 J'ai besoin de bytearrays pas bytes –

0

Votre code de serveur doit utiliser ServerSocket au lieu de Socket. Socket est utilisé pour représenter les objets Client Socket en Java.

+0

Il utilise ServerSocket l'autre socket dans mon gestionnaire est utilisé pour obtenir des informations client (il se connecte bien) le problème est avec l'envoi et la réception des tableaux d'octets –

+0

Le code que vous avez posté n'utilise pas ServerSocket n'importe où. Vous obtiendrez de l'aide plus rapidement si vous publiez le code réel du serveur et d'un client. – SCCC

+0

Je viens de mettre à jour le poste, il devrait être là maintenant –