Java Client/Server

Reply

Join Date: Sep 2006
Posts: 2
Reputation: chip1123 is an unknown quantity at this point 
Solved Threads: 0
chip1123 chip1123 is offline Offline
Newbie Poster

Java Client/Server

 
0
  #1
Sep 20th, 2006
Hey guys, I need help with this client server program I am working on. Description:
The server program takes port # as a command-line argument and performs the following
operations:
1. Opens a socket connection on the specified port
2. Listen for request from clients
3. When a client program sends a request, create a new thread to performs the appropriate
action based on the request
4. Go to step 2
The client program takes the hostname and port # on which the server process is listening as
command-line arguments and performs the following operations:
1. Open a socket connection to connect with the server process
2. Process inputs from the user
3. Send the appropriate command/request to the server process
4. Wait for the server to perform the appropriate action and respond to the client request
5. Process server response if necessary
6. Go to step 2, if the input is “QUIT” then exit.
The various commands that the client and server can process along with the action performed at
the server is given below:
LIST – Send list files in the current directory on the server (initially the directory where the
server program was started would be the current directory)
SIZE filename – Send file size of the specified file name, a negative number if file does not exist
GET filename – Send the specified file to the client process; if the specified file does not exist on
the server then the server send an error message (a negative #); filename is assumed to reside in
the current directory on server and copied to the current directory on the localhost.
PUT filename – Receive the specified file from the client; filename is assumed to be residing in
the current directory on client and is copied to the current directory on the server.
CD newdirectory – change to specified directory on the server; print an error message if the
directory does not exist.
QUIT – client program exists after closing any open connections, no action is performed on the
server.
Assume that the files are in binary format for file transfer.



Server Program:

  1. import java.net.*;
  2. import java.io.*;
  3.  
  4. public class FileServer {
  5.  
  6. static final int LISTENING_PORT = 3210;
  7.  
  8. public static void main(String[] args) {
  9.  
  10. File directory; // The directory from which the
  11. // gets the files that it serves.
  12. ServerSocket listener; // Listens for connection requests.
  13. Socket connection; // A socket for communicating with
  14. // a client.
  15.  
  16. /* Check that there is a command-line argument.
  17.   If not, print a usage message and end. */
  18.  
  19. if (args.length == 0) {
  20. System.out.println("Usage: java FileServer <directory>");
  21. return;
  22. }
  23.  
  24. /* Get the directory name from the command line, and make
  25.   it into a file object. Check that the file exists and
  26.   is in fact a directory. */
  27.  
  28. directory = new File(args[0]);
  29. if (!directory.exists()) {
  30. System.out.println("Specified directory does not exist.");
  31. return;
  32. }
  33. if (!directory.isDirectory()) {
  34. System.out.println("The specified file is not a directory.");
  35. return;
  36. }
  37.  
  38. /* Listen for connection requests from clients. For
  39.   each connection, create a separate Thread of type
  40.   ConnectionHandler to process it. The ConnectionHandler
  41.   class is defined below. The server runs until the
  42.   program is terminated, for example by a CONTROL-C. */
  43.  
  44. try {
  45. listener = new ServerSocket(LISTENING_PORT);
  46. System.out.println("Listening on port " + LISTENING_PORT);
  47. while (true) {
  48. connection = listener.accept();
  49. new ConnectionHandler(directory, connection);
  50. }
  51. } catch (Exception e) {
  52. System.out.println("Server shut down unexpectedly.");
  53. System.out.println("Error: " + e);
  54. return;
  55. }
  56.  
  57. } // end main()
  58.  
  59. static class ConnectionHandler extends Thread {
  60. // An object of this class is a thread that will
  61. // process the connection with one client. The
  62. // thread starts itself in the constructor.
  63.  
  64. File directory; // The directory from which files are served
  65.  
  66. Socket connection; // A connection to the client.
  67.  
  68. TextReader incoming; // For reading data from the client.
  69.  
  70. PrintWriter outgoing; // For transmitting data to the client.
  71.  
  72. ConnectionHandler(File dir, Socket conn) {
  73. // Constructor. Record the connection and
  74. // the directory and start the thread running.
  75. directory = dir;
  76. connection = conn;
  77. start();
  78. }
  79.  
  80. void sendList() throws Exception {
  81. // This is called by the run() method in response
  82. // to an "index" command. Send the list of files
  83. // in the directory.
  84. String[] fileList = directory.list();
  85. for (int i = 0; i < fileList.length; i++)
  86. outgoing.println(fileList[i]);
  87. outgoing.flush();
  88. outgoing.close();
  89. if (outgoing.checkError())
  90. throw new Exception("Error while transmitting data.");
  91. }
  92.  
  93. private void sendSize(String fileName) {
  94. File f = new File(fileName);
  95. if ((!f.exists()) || f.isDirectory()) {
  96. outgoing.println("error");
  97. } else {
  98. outgoing.println("ok");
  99. long length = f.length();
  100. outgoing.println(length);
  101. }
  102. // Get the number of bytes in the file
  103. }
  104.  
  105. private void ChangeDir(String fileName) throws Exception {
  106. File file = new File(directory, fileName);
  107. if ((!file.exists()) || file.isDirectory()) {
  108. outgoing.println("error");
  109. } else {
  110. directory = file;
  111. outgoing.println("ok");
  112.  
  113. }
  114. if (outgoing.checkError())
  115. throw new Exception("Error while trying to change directory.");
  116. }
  117.  
  118. private void ReceiveFile(String fileName) throws Exception {
  119. File file = new File(fileName);
  120. BufferedReader in = null;
  121. if ((file.exists())) {
  122. outgoing.println("error: file already exists");
  123. } else {
  124. outgoing.println("ok");
  125. TextReader fileIn = new TextReader(new FileReader(fileName));
  126. while (fileIn.peek() != '\0') {
  127. // Read and send lines from the file until
  128. // an end-of-file is encountered.
  129. in = new BufferedReader(new InputStreamReader(connection
  130. .getInputStream()));
  131. }
  132. }
  133. if (outgoing.checkError())
  134. throw new Exception("Error while Receiving data.");
  135. }
  136.  
  137. void sendFile(String fileName) throws Exception {
  138. // This is called by the run() command in response
  139. // to "get <fileName>" command. If the file doesn't
  140. // exist, send the message "error". Otherwise,
  141. // send the message "ok" followed by the contents
  142. // of the file.
  143. File file = new File(directory, fileName);
  144. if ((!file.exists()) || file.isDirectory()) {
  145. // (Note: Don't try to send a directory, which
  146. // shouldn't be there anyway.)
  147. outgoing.println("error");
  148. } else {
  149. outgoing.println("ok");
  150. TextReader fileIn = new TextReader(new FileReader(file));
  151. while (fileIn.peek() != '\0') {
  152. // Read and send lines from the file until
  153. // an end-of-file is encountered.
  154. String line = fileIn.getln();
  155. outgoing.println(line);
  156. }
  157. }
  158. outgoing.flush();
  159. outgoing.close();
  160. if (outgoing.checkError())
  161. throw new Exception("Error while transmitting data.");
  162. }
  163.  
  164. public void run() {
  165. // This is the method that is executed by the thread.
  166. // It creates streams for communicating with the client,
  167. // reads a command from the client, and carries out that
  168. // command. The connection is logged to standard output.
  169. // An output beginning with ERROR indicates that a network
  170. // error occurred. A line beginning with OK means that
  171. // there was no network error, but does not imply that the
  172. // command from the client was a legal command.
  173. String command = "Command not read";
  174. try {
  175. incoming = new TextReader(connection.getInputStream());
  176. outgoing = new PrintWriter(connection.getOutputStream());
  177. command = incoming.getln();
  178. if (command.equals("list")) {
  179. sendList();
  180. } else if (command.startsWith("get")) {
  181. String fileName = command.substring(3).trim();
  182. sendFile(fileName);
  183. } else if (command.startsWith("size")) {
  184. String fileName = command.substring(4).trim();
  185. sendSize(fileName);
  186. } else if (command.startsWith("put")) {
  187. String fileName = command.substring(3).trim();
  188. ReceiveFile(fileName);
  189. } else if (command.startsWith("cd")) {
  190. String fileName = command.substring(2).trim();
  191. ChangeDir(fileName);
  192. } else if (command.startsWith("exit")) {
  193. outgoing.flush();
  194. connection.close();
  195. } else {
  196. outgoing.println("unknown command");
  197. outgoing.flush();
  198. }
  199. System.out.println("OK " + connection.getInetAddress() + " "
  200. + command);
  201. } catch (Exception e) {
  202. System.out.println("ERROR " + connection.getInetAddress() + " "
  203. + command + " " + e);
  204. } finally {
  205. try {
  206. connection.close();
  207. } catch (IOException e) {
  208. }
  209. }
  210. }
  211. public static void main(String[] args) throws IOException
  212. {
  213. int PORT = 8134;
  214. InputStream inStream;
  215. DataInputStream inDataStream;
  216. OutputStream outStream;
  217. DataOutputStream outDataStream;
  218. String message="";
  219. String received="";
  220.  
  221. System.out.println("Server Started");
  222.  
  223. ServerSocket sock = new ServerSocket(PORT);
  224. Socket conn = sock.accept();
  225. do{
  226. inStream = conn.getInputStream ();
  227. inDataStream = new DataInputStream ( inStream );
  228. message = inDataStream.readUTF();
  229. System.out.println("Client sent: "+message);
  230.  
  231. DataInputStream dis = new DataInputStream(System.in);
  232. message = dis.readLine();
  233. outStream = conn.getOutputStream();
  234. outDataStream = new DataOutputStream (outStream);
  235. outDataStream.writeUTF(message);
  236. }while(!message.equals("bye"));
  237. conn.close();
  238. }
  239. }
  240.  
  241.  
  242. } // end nested class ConnectionHandler
  243. //end class FileServer




This is the Client Class:

  1. import java.io.*; // Import some needed classes
  2. import java.net.*;
  3. import java.util.*;
  4. import sun.net.*;
  5.  
  6. public class Client
  7. {
  8. public static void main(String args[]) throws IOException
  9. {
  10. int PORT = 8134;
  11. InputStream inStream;
  12. DataInputStream inDataStream;
  13. OutputStream outStream;
  14. DataOutputStream outDataStream;
  15. String message = "";
  16.  
  17. InetAddress host = InetAddress.getLocalHost();
  18. String diffHost = args[0];
  19. Socket sock = new Socket(diffHost,PORT);
  20. System.out.println("Client Started");
  21. do{
  22. System.out.println("Enter your command here: ");
  23. DataInputStream dis = new DataInputStream(System.in);
  24. message = dis.readLine();
  25. outStream = sock.getOutputStream();
  26. outDataStream = new DataOutputStream (outStream);
  27. outDataStream.writeUTF(message);
  28.  
  29. inStream = sock.getInputStream ();
  30. inDataStream = new DataInputStream ( inStream );
  31. message = inDataStream.readUTF();
  32. System.out.println("Server Sent: "+message);
  33. }while(!message.equals("bye"));
  34. }
  35. }

this is the textreader class

  1. /*
  2. This file defines the Class TextReader as a subclass of FilterReader..
  3. The TextReader provides methods for reading data expressed in human-readable
  4. ASCII text format.
  5.  
  6. This file also defines three public subclasses of RuntimeException to represent
  7. errors that can occur during input. These classes are static nested inside the
  8. TextReader class.
  9.  
  10. This is a modest variation on an earlier class called AsciiInputStream, which served
  11. a similar function for Java 1.0, where InputStreams are used instead of Readers
  12. for character input.
  13.  
  14. David Eck
  15. August 18, 1998
  16.  
  17. */
  18.  
  19.  
  20. import java.io.*;
  21.  
  22.  
  23. public class TextReader extends FilterReader {
  24.  
  25. // ************************** Exception Classes *******************************
  26.  
  27. // First, define the exceptions that can be thrown by this class. These exceptions
  28. // are subclasses of RuntimeException, so they do not require mandatory error-handling.
  29. // Also, if you prefer, you can turn off excpetions by calling the IOCheck() method.
  30. // In that case, when an exception occurs during processing by one of the methods
  31. // of the TextReader class, an errorFlag is set but no exception is thrown.
  32. // If you use this alternative error-handling strategy, then you should call the
  33. // checkError() method after each input operation to see whether the operation
  34. // completed successfully.
  35.  
  36. public static class Error extends RuntimeException {
  37. // Represents any excpetion that occurs in the TextReader Class.
  38. // In fact, only general IOExceptions are translated directly into
  39. // TextReader.Error. Other exceptions throw objects belonging
  40. // to one of the following subclasses of TextReader.Error.
  41. Error(String errorMessage) {
  42. super(errorMessage);
  43. }
  44. }
  45.  
  46. public static class FormatError extends Error {
  47. // Illegal data: an illegal number or an illegal boolean value
  48. FormatError(String errorMessage) {
  49. super(errorMessage);
  50. }
  51. }
  52.  
  53. public static class EOFError extends Error {
  54. // attempt to read past end of stream
  55. EOFError(String errorMessage) {
  56. super(errorMessage);
  57. }
  58. }
  59.  
  60.  
  61. // ***************************** Constructors ********************************
  62.  
  63. public TextReader(BufferedReader s) {
  64. super(s);
  65. }
  66.  
  67. public TextReader(Reader s) {
  68. super(new BufferedReader(s));
  69. }
  70.  
  71. public TextReader(InputStream s) {
  72. super( new BufferedReader(new InputStreamReader(s)) );
  73. }
  74.  
  75. // ***************************** Error Checking *****************************
  76.  
  77. public void IOCheck(boolean throwExceptions) { // call IOCheck(false) to turn
  78. throwExceptionOnError = throwExceptions; // off exceptions, then check
  79. } // for errors by calling checkError()
  80.  
  81. public boolean error() { // returns true if the most recent input operation on
  82. return errorFlag; // this TextReader produced an error. An error
  83. } // message can be retrieved by calling getErrorMessage()
  84.  
  85. public String getErrorMessage() { // if the most recent operation on
  86. return errorFlag ? errorMessage : null; // this TextReader produced an error, this
  87. } // gets an error message for that error
  88.  
  89. // *************************** Input Methods ********************************
  90.  
  91. // peek() -- returns the next character about to be read from the stream,
  92. // without removing it from the stream. '\n' is returned if the next
  93. // thing in the stream is end-of-line. '\0' is returned if the next
  94. // thing is end-of-file. (There is no way for peek() to distinguish
  95. // between EOF and a null character in the input data. Use eof() to
  96. // test for end-of-file.)
  97.  
  98. // getAnyChar() -- reads and returns the next character in the stream, even if it
  99. // is a whitespace character. It is an error to read past end-of-file.
  100. // (Note that getChar() skips over whitespace characters before reading.)
  101.  
  102. // getChar(), getByte(), etc. -- skip over whitespace characters, then try to read a
  103. // value of the specified type. An error can occur if the right type of data
  104. // is not found. A "word" is any sequence of non-whitespace characters.
  105. // A "boolean" is one of the words (ignoring case) "true", "false", "yes", "no"
  106. // "t", "f", "y", "n", "0", "1". An "Alpha" is a sequence of letters. getAlpha()
  107. // is a special case in that it will skip over all non-letters before reading,
  108. // rather than just skipping whitespace characters.
  109.  
  110. // getln() -- reads all characters up to the next end-of-line and returns them
  111. // as a String. The end-of-line is then read and discarded.
  112.  
  113. // getlnChar(), getlnByte() etc. -- Work the same as getChar(), etc., except that
  114. // after the value is read, any other characters on the same line, including the
  115. // end-of-line, are read and discarded.
  116.  
  117. // eoln() -- this first reads and discards any spaces and tabs. Then tests whether
  118. // the next thing in the stream is an end-of-line. The end-of-file also counts
  119. // as an end of line. If you want to test for eoln without discarding spaces
  120. // and tabs, check whether peek() == '\n' or '\0'.
  121.  
  122. // eof() -- this first reads and discards any spaces, ends-of-line and tabs. Then tests
  123. // whether the next thing in the stream is the end-of-file. If you want to test for
  124. // eof without discarding spaces, ends-of-line, and tabs, check whether peek() == '\0'.
  125.  
  126. // skipWhiteSpace() -- reads and discards any whitespace characters (spaces, tabs, and
  127. // end-of-lines). Stops when the next character is a non-whitespace character or is eof.
  128.  
  129. // skipNonLetters() -- reads and discards any non-letters, stopping when the next character
  130. // is a letter or the end-of-file.
  131.  
  132. public char peek() { errorFlag = false; return lookChar(); }
  133.  
  134. public char getAnyChar() { errorFlag = false; return readChar(); }
  135.  
  136. public char getChar() { errorFlag = false; skipWhiteSpace(); return readChar(); }
  137. public byte getByte() { errorFlag = false; return (byte)readInteger(-128L,127L); }
  138. public short getShort() { errorFlag = false; return (short)readInteger(-32768L,32767L); }
  139. public int getInt() { errorFlag = false; return (int)readInteger((long)Integer.MIN_VALUE, (long)Integer.MAX_VALUE); }
  140. public long getLong() { errorFlag = false; return readInteger(Long.MIN_VALUE, Long.MAX_VALUE); }
  141. public float getFloat() { errorFlag = false; return readFloat(); }
  142. public double getDouble() { errorFlag = false; return readDouble(); }
  143. public boolean getBoolean() { errorFlag = false; return readBoolean(); }
  144. public String getWord() { errorFlag = false; return readWord(); }
  145. public String getAlpha() { errorFlag = false; return readAlpha(); }
  146.  
  147. public String getln() { errorFlag = false; return readLine(); }
  148.  
  149. public char getlnChar() { char x=getChar(); dropLine(); return x; }
  150. public byte getlnByte() { byte x=getByte(); dropLine(); return x; }
  151. public short getlnShort() { short x=getShort(); dropLine(); return x; }
  152. public int getlnInt() { int x=getInt(); dropLine(); return x; }
  153. public long getlnLong() { long x=getLong(); dropLine(); return x; }
  154. public float getlnFloat() { float x=getFloat(); dropLine(); return x; }
  155. public double getlnDouble() { double x=getDouble(); dropLine(); return x; }
  156. public boolean getlnBoolean() { boolean x=getBoolean(); dropLine(); return x; }
  157. public String getlnWord() { String x=getWord(); dropLine(); return x; }
  158. public String getlnAlpha() { String x=getAlpha(); dropLine(); return x; }
  159.  
  160. public boolean eoln() {
  161. char ch = lookChar();
  162. while (!EOF && !errorFlag && (ch == ' ' || ch == '\t')) {
  163. readChar();
  164. ch = lookChar();
  165. }
  166. return (ch == '\n' || EOF);
  167. }
  168.  
  169. public boolean eof() {
  170. char ch = lookChar();
  171. while (!EOF && !errorFlag && (ch == ' ' || ch == '\n' || ch == '\t')) {
  172. readChar();
  173. ch = lookChar();
  174. }
  175. return EOF;
  176. }
  177.  
  178. public void skipWhiteSpace() {
  179. char ch = lookChar();
  180. while (!errorFlag && (ch == ' ' || ch == '\n' || ch == '\t')) {
  181. readChar();
  182. ch = lookChar();
  183. }
  184. }
  185.  
  186. public void skipNonLetters() {
  187. char ch = lookChar();
  188. while (!errorFlag && !EOF && !Character.isLetter(ch)) {
  189. readChar();
  190. ch = lookChar();
  191. }
  192. }
  193.  
  194. public void close() {
  195. errorFlag = false;
  196. try {
  197. in.close();
  198. }
  199. catch (IOException e) {
  200. errorFlag = true;
  201. errorMessage = e.toString();
  202. }
  203. }
  204.  
  205. //*************************** private implementation stuff ***********************
  206.  
  207. private int lookAhead = -1; // one-character buffer; -1 indicates the buffer is empty
  208. private boolean errorFlag = false; // set to true if most recent operation produced an error
  209. private String errorMessage = ""; // error message for the most recent error
  210. private boolean EOF = false; // has the end-of-stream been encountered?
  211. private boolean throwExceptionOnError = true; // determines which type of error-handling is used
  212.  
  213. // Three utility routines for throwing exceptions.
  214.  
  215. private void doError(String message) {
  216. errorFlag = true;
  217. errorMessage = message;
  218. if (throwExceptionOnError)
  219. throw new Error(message);
  220. }
  221.  
  222. private void doFormatError(String message) {
  223. errorFlag = true;
  224. errorMessage = message;
  225. if (throwExceptionOnError)
  226. throw new FormatError(message);
  227. }
  228.  
  229. private void doEOFError(String message) {
  230. errorFlag = true;
  231. errorMessage = message;
  232. if (throwExceptionOnError)
  233. throw new FormatError(message);
  234. }
  235.  
  236. // The remaining methods are basic methods for reading the various types of
  237. // data from the stream
  238.  
  239. private char readChar() {
  240. char ch = lookChar();
  241. if (EOF)
  242. doEOFError("Attempt to read past end-of-data in input stream.");
  243. lookAhead = -1;
  244. return ch;
  245. }
  246.  
  247. private boolean possibleLineFeedPending = false; // for dealing with \r\n pairs
  248.  
  249. private char lookChar() {
  250. if (lookAhead != -1) {
  251. if (lookAhead == '\r')
  252. return '\n';
  253. else
  254. return (char)lookAhead;
  255. }
  256. if (EOF)
  257. return '\0';
  258. try {
  259. int n = in.read();
  260. if (n == '\n' && possibleLineFeedPending) { // ignore \n of \r\n pair
  261. n = in.read();
  262. }
  263. possibleLineFeedPending = (n == '\r');
  264. lookAhead = n;
  265. if (lookAhead == -1) {
  266. EOF = true;
  267. return '\0';
  268. }
  269. }
  270. catch (IOException e) {
  271. doError(e.getMessage());
  272. }
  273. if (lookAhead == '\r') // represent all eoln's with \n
  274. lookAhead = '\n';
  275. return (char)lookAhead;
  276. }
  277.  
  278. private void dropLine() {
  279. while (!errorFlag) {
  280. if (lookChar() == '\0')
  281. return;
  282. if (readChar() == '\n')
  283. return;
  284. }
  285. }
  286.  
  287. private String readLine() {
  288. StringBuffer s = new StringBuffer(100);
  289. char ch = readChar();
  290. while (!errorFlag && ch != '\n') {
  291. s.append(ch);
  292. ch = lookChar();
  293. if (ch == '\0')
  294. break;
  295. ch = readChar();
  296. }
  297. return s.toString();
  298. }
  299.  
  300. private String readWord() {
  301. skipWhiteSpace();
  302. if (errorFlag)
  303. return null;
  304. StringBuffer s = new StringBuffer(50);
  305. char ch = lookChar();
  306. if (EOF) {
  307. doEOFError("Attempt to read past end-of-data");
  308. return null;
  309. }
  310. while (!errorFlag && !EOF && ch != '\n' && ch != ' ' && ch != '\t') {
  311. s.append(readChar());
  312. ch = lookChar();
  313. }
  314. return s.toString();
  315. }
  316.  
  317.  
  318. private String readAlpha() {
  319. skipNonLetters();
  320. if (errorFlag)
  321. return null;
  322. StringBuffer s = new StringBuffer(50);
  323. char ch = lookChar();
  324. if (EOF) {
  325. doEOFError("Attempt to read past end-of-data");
  326. return null;
  327. }
  328. while (!errorFlag && Character.isLetter(ch)) {
  329. s.append(readChar());
  330. ch = lookChar();
  331. }
  332. return s.toString();
  333. }
  334.  
  335.  
  336. public float readFloat() {
  337. double d = readDouble();
  338. if (errorFlag)
  339. return Float.NaN;
  340. if (Math.abs(d) > Float.MAX_VALUE)
  341. doFormatError("Input number outside of legal range for values of type float");
  342. return (float)d;
  343. }
  344.  
  345. public double readDouble() {
  346. double x = Double.NaN;
  347. StringBuffer s=new StringBuffer(50);
  348. skipWhiteSpace();
  349. char ch = lookChar();
  350. if (ch == '-' || ch == '+') {
  351. s.append(readChar());
  352. skipWhiteSpace();
  353. ch = lookChar();
  354. }
  355. if ( (ch < '0' || ch > '9') && (ch != '.') ) {
  356. if (EOF)
  357. doEOFError("Expecting a floating-point number and found end-of-data");
  358. else
  359. doFormatError("Expecting a floating-point number and found \"" + ch + "\"" );
  360. return Double.NaN;
  361. }
  362. boolean digits = false;
  363. while (ch >= '0' && ch <= '9') {
  364. s.append(readChar());
  365. ch = lookChar();
  366. digits = true;
  367. }
  368. if (ch == '.') {
  369. s.append(readChar());
  370. ch = lookChar();
  371. while (ch >= '0' && ch <= '9') {
  372. s.append(readChar());
  373. ch = lookChar();
  374. digits = true;
  375. }
  376. }
  377. if (!digits) {
  378. doFormatError("No digits found in floating-point input.");
  379. return Double.NaN;
  380. }
  381. if (ch == 'E' || ch == 'e') {
  382. s.append(readChar());
  383. ch = lookChar();
  384. if (ch == '-' || ch == '+') {
  385. s.append(readChar());
  386. ch = lookChar();
  387. }
  388. if ( (ch < '0' || ch > '9') && (ch != '.') ) {
  389. if (EOF)
  390. doEOFError("Expecting exponent for a floating-point number and found end-of-data");
  391. else
  392. doFormatError("Expecting exponent for a floating-point number and found \"" + ch + "\"");
  393. return Double.NaN;
  394. }
  395. while (ch >= '0' && ch <= '9') {
  396. s.append(readChar());
  397. ch = lookChar();
  398. }
  399. }
  400. String str = s.toString();
  401. Double d;
  402. try {
  403. d = new Double(str);
  404. x = d.doubleValue();
  405. }
  406. catch (NumberFormatException e) {
  407. x = Double.NaN;
  408. }
  409. if (Double.isNaN(x) || Double.isInfinite(x)) {
  410. doFormatError("Illegal floating point number");
  411. return Double.NaN;
  412. }
  413. return x;
  414. }
  415.  
  416. public boolean readBoolean() {
  417. boolean ans = false;
  418. String s = getWord();
  419. if (errorFlag)
  420. return false;
  421. if ( s.equalsIgnoreCase("true") || s.equalsIgnoreCase("t") ||
  422. s.equalsIgnoreCase("yes") || s.equalsIgnoreCase("y") ||
  423. s.equals("1") ) {
  424. ans = true;
  425. }
  426. else if ( s.equalsIgnoreCase("false") || s.equalsIgnoreCase("f") ||
  427. s.equalsIgnoreCase("no") || s.equalsIgnoreCase("n") ||
  428. s.equals("0") ) {
  429. ans = false;
  430. }
  431. else
  432. doFormatError("Illegal input for value of type boolean: \"" + s + "\"");
  433. return ans;
  434. }
  435.  
  436.  
  437. private long readInteger(long min, long max) { // read long integer, limited to specified range
  438. skipWhiteSpace();
  439. if (errorFlag)
  440. return 0;
  441. char sign = '+';
  442. if (lookChar() == '-' || lookChar() == '+') {
  443. sign = getChar();
  444. skipWhiteSpace();
  445. }
  446. long n = 0;
  447. char ch = lookChar();
  448. if (ch < '0' || ch > '9') {
  449. if (EOF)
  450. doEOFError("Expecting an integer and found end-of-data");
  451. else
  452. doFormatError("Expecting an integer and found \"" + ch + "\"");
  453. return 0;
  454. }
  455. while (!errorFlag && ch >= '0' && ch <= '9') {
  456. readChar();
  457. n = 10*n + (int)ch - (int)'0';
  458. if (n < 0) {
  459. doFormatError("Integer value outside of legal range");
  460. return 0;
  461. }
  462. ch = lookChar();
  463. }
  464. if (sign == '-')
  465. n = -n;
  466. if (n < min || n > max) {
  467. doFormatError("Integer value outside of legal range");
  468. return 0;
  469. }
  470. return n;
  471. }
  472.  
  473. // Override the read() methods from FilterReader so that they will work if a
  474. // TextReader is wrapped inside another file. (This is necessary to take
  475. // lookAhead into account.)
  476.  
  477. public int read() throws IOException {
  478. if (lookAhead == -1)
  479. return super.read();
  480. else {
  481. int x = lookAhead;
  482. lookAhead = -1;
  483. return x;
  484. }
  485. }
  486.  
  487. public int read(char[] buffer, int offset, int count) throws IOException {
  488. if (lookAhead == -1 || count <= 0)
  489. return super.read(buffer,offset,count);
  490. else if (count == 1) {
  491. buffer[offset] = (char)lookAhead;
  492. lookAhead = -1;
  493. return 1;
  494. }
  495. else {
  496. buffer[offset] = (char)lookAhead;
  497. lookAhead = -1;
  498. int ct = super.read(buffer,offset+1,count-1);
  499. return ct + 1;
  500. }
  501. }
  502.  
  503. } // end of class TextReader
Reply With Quote Quick reply to this message  
Join Date: Feb 2006
Posts: 2,281
Reputation: masijade has much to be proud of masijade has much to be proud of masijade has much to be proud of masijade has much to be proud of masijade has much to be proud of masijade has much to be proud of masijade has much to be proud of masijade has much to be proud of masijade has much to be proud of 
Solved Threads: 243
masijade's Avatar
masijade masijade is online now Online
Nearly a Posting Maven

Re: Java Client/Server

 
0
  #2
Sep 21st, 2006
So what is your soecific problem? What error are you getting? What effect are you observing that you did not expect?
Java Programmer and Sun Systems Administrator

----------------------------------------------

Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.
--Brian Kernighan
Reply With Quote Quick reply to this message  
Join Date: Sep 2006
Posts: 2
Reputation: chip1123 is an unknown quantity at this point 
Solved Threads: 0
chip1123 chip1123 is offline Offline
Newbie Poster

Re: Java Client/Server

 
0
  #3
Sep 21st, 2006
I am not sure if my Client/Server is working correctly. I am trying to get them to where they will do what the specs ask. I am not sure if I am even approaching it correctly because I have no experience in this area and was wondering if someone could let me know if it was close to being right or not and what I needed to change.

1) I am unsure about the command line arguments and how to use them to look for server and port #.

2) Once #1 works, then I can make sure the client and server connect- right now I am having a hard time figuring out how to make them connect correctly.

3) Don't know if I am getting the upload/download sections working correctly.

4) Not sure how to change directories in java.

5) I am going to I'm also going to list errors below:

The client gives me this error:
java.lang.ArrayIndexOutOfBoundsException: 0
at Client.main(Client.java:29)
Exception in thread "main"

The server gives me this error, but only if I have it used more than once:
java.net.BindException: Address already in use: JVM_Bind
at java.net.PlainSocketImpl.socketBind(Native Method)
at java.net.PlainSocketImpl.bind(PlainSocketImpl.java:331)
at java.net.ServerSocket.bind(ServerSocket.java:318)
at java.net.ServerSocket.<init>(ServerSocket.java:185)
at java.net.ServerSocket.<init>(ServerSocket.java:97)
at FileServer$ConnectionHandler.main(FileServer.java:240)
Exception in thread "main"
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC