2017-09-28 4 views
-1

Je viens de commencer à la fois avec Java et la mise en réseau avec les serveurs et les clients. Bien que je comprenne les bases de ce qui se passe, je luttais pour mettre tout cela ensemble et faire ce que je voulais faire dans le titre. Je pouvais faire ceci pour envoyer un message au serveur, mais je me demandais comment je transformerais le message en une chaîne d'entrée de l'utilisateur, et aussi comment envoyer plusieurs messages entre le client et le serveur merciComment changer ce code pour permettre l'envoi de plus d'un message d'entrée utilisateur entre le client et le serveur

SERVEUR

import java.io.*; 
import java.net.*; 

public class Server { 

//Main Method:- called when running the class file. 
public static void main(String[] args){ 

    //Portnumber:- number of the port we wish to connect on. 
    int portNumber = 15882; 
    try{ 
     //Setup the socket for communication and accept incoming communication 
     ServerSocket serverSoc = new ServerSocket(portNumber); 
     Socket soc = serverSoc.accept(); 

     //Catch the incoming data in a data stream, read a line and output it to the console 
     DataInputStream dataIn = new DataInputStream(soc.getInputStream()); 
     System.out.println("--> " + dataIn.readUTF()); 

     //Remember to close the socket once we have finished with it. 
     soc.close(); 
    } 
    catch (Exception except){ 
     //Exception thrown (except) when something went wrong, pushing message to the console 
     System.out.println("Error --> " + except.getMessage()); 
    } 
}} 

CLIENT

import java.io.*; 
import java.net.*; 


public class Client { 

//Main Method:- called when running the class file. 
public static void main(String[] args){ 

    //Portnumber:- number of the port we wish to connect on. 
    int portNumber = 15882; 
    //ServerIP:- IP address of the server. 
    String serverIP = "localhost"; 

    try{ 
     //Create a new socket for communication 
     Socket soc = new Socket(serverIP,portNumber); 

     //Create the outputstream to send data through 
     DataOutputStream dataOut = new DataOutputStream(soc.getOutputStream()); 

     //Write message to output stream and send through socket 
     dataOut.writeUTF("Hello other world!"); 
     dataOut.flush(); 

     //close the data stream and socket 
     dataOut.close(); 
     soc.close(); 
    } 
    catch (Exception except){ 
     //Exception thrown (except) when something went wrong, pushing message to the console 
     System.out.println("Error --> " + except.getMessage()); 
    } 
}} 

Répondre

0

Il y a quelques "problèmes" avec votre code.

  1. Vous ne devez fermer le serveur ServerSocket que si vous avez terminé.
  2. Vous devez gérer le client nouvellement connecté dans un thread pour permettre à plusieurs clients d'envoyer simultanément des messages.

1.

vous pouvez facilement envelopper votre code à l'intérieur d'une boucle while.

boolean someCondition = true; 
try{ 
    //Setup the socket for communication and accept incoming communication 
    ServerSocket serverSoc = new ServerSocket(portNumber); 
    // repeat the whole process over and over again. 
    while(someCondition) { 
     Socket soc = serverSoc.accept(); 

     //Catch the incoming data in a data stream, read a line and output it to the console 
     DataInputStream dataIn = new DataInputStream(soc.getInputStream()); 
     System.out.println("--> " + dataIn.readUTF()); 
    } 

    //Remember to close the socket once we have finished with it. 
    soc.close(); 
} 

Votre programme doit maintenant continuer à accepter les clients. Mais seulement un à la fois. Vous pouvez maintenant terminer le serveur en arrêtant le programme ou en changeant le someCondition à false et en acceptant le client suivant.

Un peu plus avancé serait, pour arrêter le ServerSocket pour arrêter le programme et attraper l'exception dans la boucle while.


2.

Pour permettre à plusieurs clients à traiter simultaniously, vous devez emballer la poignée dans un autre thread.

private ExecutorService threadPool = Executors.newCachedThreadPool(); 

boolean someCondition = true; 
try{ 
    //Setup the socket for communication and accept incoming communication 
    ServerSocket serverSoc = new ServerSocket(portNumber); 
    // repeat the whole process over and over again. 
    while(someCondition) { 
     Socket soc = serverSoc.accept(); 

      //Catch the incoming data in a data stream, read a line and output it to the console in a new Thread. 
     threadPool.submit(() -> { 
      DataInputStream dataIn = new 
      DataInputStream(soc.getInputStream()); 
      System.out.println("--> " + dataIn.readUTF()); 
     } 
    } 

    //Remember to close the socket once we have finished with it. 
    soc.close(); 
} 

La partie intérieure du bloc threadPool.submit peut être spécifié comme une instance personnalisée de l'interface Runnable comme une méthode, pour appeler à l'aide method reference.
Je suppose que vous connaissez ThreadPools. They have multiple advantages over Threads

Cela devrait vous permettre d'utiliser n'importe quel nombre de clients.

Note: Ceci n'est pas bien conçu, mais uniquement pour les porpurses de démonstration.