Problem mit Hashtables and Server-Client Kommunikation

  • Problem mit Hashtables and Server-Client Kommunikation

    Hallo,
    ich bringe mir selbst Java bei und bin bei einer Aufgabe auf folgende Probleme gestoßen:

    Die Aufgabe ist Folgende:
    - Verwende eine (vorgegebene) Hashtable und ermögliche 3 verschiedene Abfragen (Eingabe eines Key und Finden des zugehörigen Value, Eingabe eines Value und Finden des zugehörigen Keys und Ausgabe der gesamten Daten der Hashtable
    - Die Abfragen geschehen über Server und Client

    Meine Probleme sind:

    Das mit dem Finden des Value habe ich folgendermaßen mit Hilfe von Map probiert:

    Quellcode

    1. while (it.hasNext()) {
    2. Map.Entry entry = (Map.Entry)it.next();
    3. if (entry.equals("2343"))
    4. System.out.println(
    5. (String)entry.getKey() + " >> " +
    6. (String)entry.getValue()
    7. );


    Allerdings bekomme ich nie irgend etwas zurück, obwohl die Zahl 2343 in der Hashtable und damit auch im Datensatz enthalten ist. Lasse ich die Zeile mit if weg, gibt er mir auch artig die gesamte Liste aus. Ich möchte aber in diesem Falle nur den zu "2343" gehörigen Key haben, nicht alle.
    Was mache ich falsch?


    Ein weiteres Problem habe ich bei Ausgabe der gesamten Hashtable von einem Server an einen Client. Folgenden Code habe ich dazu:

    In der class Client:

    Quellcode

    1. // Send request for all staff
    2. pw.println("A");
    3. //Read what is sent back from server
    4. String all = bf.readLine();
    5. if(all.charAt(0)=='*')
    6. {
    7. // Error name not recognised
    8. queryResults.setText("Error");
    9. }
    10. else
    11. {
    12. //Place number on the Text area with message
    13. queryResults.setText("");
    14. queryResults.setText("All Staff: "+ all);
    15. }
    Alles anzeigen


    In der class Server:

    Quellcode

    1. case'A': {
    2. // All staff required
    3. Enumeration e = numbers.keys();
    4. while (e.hasMoreElements()) {
    5. String all = (String)e.nextElement();
    6. pw.println(all + ": " + numbers.get(all));
    7. }
    8. }


    Ich bekomme auch eine Ausgabe. Aber leider nicht die gesamte Liste, sondern nur das erste Key-Value-Paar. Verwende ich den Code aus dem Server und ersetze pw.println by System.out.println bekomme ich die gesamte Liste ausgegeben, nur leider nicht über per Server-Client-Kommunikation
    Was mache ich hier falsch?


    Jede Hilfe ist willkommen.

    Liebe Grüße


    Anja
  • Hi, sorry für die späte Antwort:
    Problem1 löst du indem du nicht das ganze Objekt, sondern nur den Key vergleichst.

    Quellcode

    1. Iterator it = h.entrySet().iterator();
    2. while (it.hasNext()) {
    3. Map.Entry entry = (Map.Entry)it.next();
    4. if (entry.getKey().equals("2343"))
    5. System.out.println(
    6. (String)entry.getKey() + " >> " +
    7. (String)entry.getValue()
    8. );
    9. }


    Bei deinem 2ten Problem kenne ich deine Funktionen zwar nicht.
    aber wenn du eine set Methode aufrust, dann wirst du damit vermutlich nur eine Variable setzen (das heißt bei weiteren Aufrufen immer überschreiben)

    Verwende also besser

    Quellcode

    1. queryResults.setText("\nAll Staff: "+ all);

    statt

    Quellcode

    1. queryResults.setText("");
    2. queryResults.setText("All Staff: "+ all);


    \n steht für einen Zeilenumbruch
  • Hallo D0nUt,
    im folgenden sende ich dann mal den ganzen Code rüber:

    1. Server

    Quellcode

    1. import java.io.*;
    2. import java.net.*;
    3. import java.util.*;
    4. public class Server
    5. {
    6. public static void main(String[] args)
    7. {
    8. Hashtable numbers = new Hashtable();
    9. // Data of the hashtable
    10. numbers.put("Ince","2399");
    11. numbers.put("Roberts","2900");
    12. numbers.put("Timms","3400");
    13. numbers.put("Rowlands","2299");
    14. numbers.put("Eustace","3358");
    15. numbers.put("Lord","2212");
    16. numbers.put("Willis","3400");
    17. numbers.put("Wallace","2218");
    18. numbers.put("Crichton","3300");
    19. numbers.put("Richards","2289");
    20. numbers.put("Williams","1129");
    21. int count = 0; //Counts successful connections
    22. PrintWriter pw = null;
    23. BufferedReader bf = null;
    24. Socket s = null;
    25. ServerSocket ss = null;
    26. String clientLine= ""; //Used for reading lines from client
    27. String nameId = "";
    28. String request = null;
    29. try {
    30. // Using port 1200 for communication
    31. System.out.println("...Setting up server socket");
    32. ss = new ServerSocket(1200);
    33. //Loop around waiting for client requests
    34. while(true) {
    35. count++;
    36. System.out.println("...Waiting for connection "+count);
    37. s = ss.accept();
    38. // Connection accepted
    39. pw = new PrintWriter(s.getOutputStream(), true);
    40. bf = new BufferedReader(new InputStreamReader(s.getInputStream()));
    41. // Read command from client
    42. clientLine = bf.readLine();
    43. switch (clientLine.charAt(0)){
    44. case'A': {
    45. // All staff required
    46. Enumeration e = numbers.keys();
    47. while (e.hasMoreElements()) {
    48. String all = (String)e.nextElement();
    49. pw.print(all + ", ");
    50. }
    51. }
    52. case 'T': {
    53. // number of member of staff required
    54. nameId = clientLine.substring(1, clientLine.length());
    55. if(numbers.containsKey(nameId))
    56. pw.println(numbers.get(nameId));
    57. else pw.println("not found");
    58. }
    59. case 'N': {
    60. // name corresponding to number needed
    61. nameId = clientLine.substring(1, clientLine.length());
    62. Iterator it = numbers.keySet().iterator();
    63. while (it.hasNext()) {
    64. String key = (String)it.next();
    65. Object value = numbers.get(key);
    66. if (value.equals(nameId))
    67. pw.println(
    68. key + ", "
    69. );
    70. else
    71. System.out.println("not found");
    72. }
    73. }
    74. }
    75. pw.close();
    76. bf.close();
    77. s.close();
    78. }
    79. }catch (Exception e)
    80. {
    81. System.out.println("Problem establishing a connection"+e);
    82. }
    83. }
    84. }
    Alles anzeigen



    2. Client

    Quellcode

    1. import java.awt.*;
    2. import com.borland.jbcl.layout.*;
    3. import javax.swing.*;
    4. import java.awt.event.*;
    5. import java.io.*;
    6. import java.net.*;
    7. public class Client extends JFrame
    8. {
    9. PrintWriter pw;
    10. BufferedReader bf;
    11. String nameIdentity;
    12. // Create new design objects
    13. XYLayout xYLayout1 = new XYLayout();
    14. JButton nameButton = new JButton();
    15. JButton numberButton = new JButton();
    16. JButton allButton = new JButton();
    17. JTextArea queryResults = new JTextArea();
    18. JTextField request = new JTextField();
    19. JLabel resultsLabel = new JLabel();
    20. JLabel jLabel1 = new JLabel();
    21. JButton quitButton = new JButton();
    22. public Client() {
    23. try {
    24. jbInit();
    25. }
    26. catch(Exception e) {
    27. e.printStackTrace();
    28. }
    29. }
    30. // Assign visible text labels to design objects and set the ActionListener
    31. private void jbInit() throws Exception {
    32. nameButton.setText("Find Name");
    33. nameButton.addActionListener(new java.awt.event.ActionListener() {
    34. public void actionPerformed(ActionEvent e) {
    35. nameButton_actionPerformed(e);
    36. }
    37. });
    38. this.getContentPane().setLayout(xYLayout1);
    39. numberButton.setText("Find Phone Number");
    40. numberButton.addActionListener(new java.awt.event.ActionListener() {
    41. public void actionPerformed(ActionEvent e) {
    42. numberButton_actionPerformed(e);
    43. }
    44. });
    45. this.getContentPane().setLayout(xYLayout1);
    46. allButton.setText("Find all staff");
    47. allButton.addActionListener(new java.awt.event.ActionListener() {
    48. public void actionPerformed(ActionEvent e) {
    49. allButton_actionPerformed(e);
    50. }
    51. });
    52. resultsLabel.setText("Results");
    53. jLabel1.setText("Request");
    54. quitButton.setText("Quit");
    55. quitButton.addActionListener(new java.awt.event.ActionListener() {
    56. public void actionPerformed(ActionEvent e) {
    57. quitButton_actionPerformed(e);
    58. }
    59. });
    60. // Layout of design objects
    61. xYLayout1.setWidth(468);
    62. xYLayout1.setHeight(300);
    63. this.getContentPane().add(allButton, new XYConstraints(280, 9, 180, 25));
    64. this.getContentPane().add(nameButton, new XYConstraints(280, 48, 180, 25));
    65. this.getContentPane().add(numberButton, new XYConstraints(280, 88, 180, 25));
    66. this.getContentPane().add(queryResults, new XYConstraints(10, 101, 230, 189));
    67. this.getContentPane().add(request, new XYConstraints(10, 55, 230, 24));
    68. this.getContentPane().add(jLabel1, new XYConstraints(10, 28, -1, -1));
    69. this.getContentPane().add(resultsLabel, new XYConstraints(10, 82, -1, -1));
    70. this.getContentPane().add(quitButton, new XYConstraints(382, 252, 76, 25));
    71. }
    72. public static void main(String[] args)
    73. {
    74. System.out.println("Student answer being executed");
    75. Client ec = new Client();
    76. ec.setSize(500,350);
    77. ec.setVisible(true);
    78. }
    79. void nameButton_actionPerformed(ActionEvent e)
    80. {
    81. // Code for processing when name button is clicked
    82. // Pick up string in nameIdentity text field
    83. nameIdentity = request.getText();
    84. try
    85. {
    86. // Socket established on port 1200 of server
    87. Socket s = new Socket("127.0.0.1", 1200);
    88. // Set up reader and writer
    89. pw = new PrintWriter(s.getOutputStream(),true);
    90. bf = new BufferedReader(new InputStreamReader(s.getInputStream()));
    91. // Send request for name for number
    92. pw.println("N"+nameIdentity);
    93. //Read name sent back from server
    94. String name = bf.readLine();
    95. if(name.charAt(0)=='*')
    96. {
    97. // Error: name not recognised
    98. queryResults.setText("Error");
    99. }
    100. else
    101. {
    102. //Place name on the Text area with message
    103. queryResults.setText("\nNumber "+nameIdentity+" belongs to "+name);
    104. }
    105. // close down connection, in a practical system this would be
    106. // closed down when the client terminated
    107. pw.close();
    108. s.close();
    109. bf.close();
    110. }catch(Exception ex)
    111. {System.out.println("Problem establishing a connection ");}
    112. }
    113. void numberButton_actionPerformed(ActionEvent e)
    114. {
    115. // Code for processing when number button is clicked
    116. // Pick up string in nameIdentity text field
    117. nameIdentity = request.getText();
    118. try
    119. {
    120. // Socket established on port 1200 of server
    121. Socket s = new Socket("127.0.0.1", 1200);
    122. // Set up reader and writer
    123. pw = new PrintWriter(s.getOutputStream(),true);
    124. bf = new BufferedReader
    125. (new InputStreamReader(s.getInputStream()));
    126. // Send request for number of name
    127. pw.println("T"+nameIdentity);
    128. //Read number sent back from server
    129. String number = bf.readLine();
    130. if(number.charAt(0)=='*')
    131. {
    132. // Error name not recognised
    133. queryResults.setText("Error");
    134. }
    135. else
    136. {
    137. //Place number on the Text area with message
    138. queryResults.setText("");
    139. queryResults.setText("Number of "+nameIdentity+" = "+number);
    140. }
    141. // close down connection, in a practical system this would be
    142. // closed down when the client terminated
    143. pw.close();
    144. s.close();
    145. bf.close();
    146. }catch(Exception ex)
    147. {System.out.println("Problem establishing a connection ");}
    148. }
    149. void allButton_actionPerformed(ActionEvent e)
    150. {
    151. // Code for processing when all button is clicked
    152. try
    153. {
    154. // Socket established on port 1200 of server
    155. Socket s = new Socket("127.0.0.1", 1200);
    156. // Set up reader and writer
    157. pw = new PrintWriter(s.getOutputStream(),true);
    158. bf = new BufferedReader
    159. (new InputStreamReader(s.getInputStream()));
    160. // Send request for all staff
    161. pw.println("A");
    162. //Read what is sent back from server
    163. String all = bf.readLine();
    164. if(all.charAt(0)=='*')
    165. {
    166. // Error name not recognised
    167. queryResults.setText("Error");
    168. }
    169. else
    170. {
    171. //Place number on the Text area with message
    172. queryResults.setText("");
    173. queryResults.setText("\nAll Staff: "+ all);
    174. }
    175. // close down connection, in a practical system this would be
    176. // closed down when the client terminated
    177. pw.close();
    178. s.close();
    179. bf.close();
    180. }catch(Exception ex)
    181. {System.out.println("Problem establishing a connection ");}
    182. }
    183. // code for processing when quit button is pressed
    184. void quitButton_actionPerformed(ActionEvent e) {
    185. System.exit(0);
    186. }
    187. }
    Alles anzeigen

    Das Problem habe ich sowohl beim Ausgeben der gesamten Daten der Hashtable als auch im Falle, dass eine Nummer (Value) zwei verschiedenen Personen (Keys) zugeordnet werden kann.
    In beiden Fällen bekomme ich entweder nur ein Wertepaar (bei Verwendung von pw.println im Server) oder alle erforderlichen Wertepaare, aber alle aneinandergereiht (bei Verwendung von pw.print) im Client ausgegeben.

    Durch Tests habe ich festgestellt, dass der Server perfekt funktioniert und alle gewünschten Ausgaben liefert (ich hatte ihn einfach mal direkt ausgeben lassen, statt über den Client zu gehen). Also nehme ich an, dass irgendwo bei der Übergabe an den Client der Wurm drin ist.

    Vielen Dank schon mal für die Hilfe

    Liebe Grüße

    Anja