TCPTools.Mod 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. MODULE TCPTools; (** AUTHOR "staubesv"; PURPOSE "Some utilitiy commands for TCP"; *)
  2. IMPORT
  3. Streams, Commands, Files, IP, TCP, DNS;
  4. CONST
  5. BufferSize = 4096;
  6. (** Send a file to hostname:port. This can be used to send a PS file to a PS capable network printer (use port 9100) *)
  7. PROCEDURE SendFile*(context : Commands.Context); (** hostname port filename ~ *)
  8. VAR
  9. hostname, adrStr : ARRAY 256 OF CHAR; ipAdr : IP.Adr; port: LONGINT; res: WORD;
  10. filename : Files.FileName; file : Files.File; reader : Files.Reader;
  11. offset, len : LONGINT;
  12. buffer : POINTER TO ARRAY OF CHAR;
  13. connection : TCP.Connection;
  14. writer : Streams.Writer;
  15. BEGIN
  16. context.arg.SkipWhitespace; context.arg.String(hostname);
  17. context.arg.SkipWhitespace; context.arg.Int(port, FALSE);
  18. context.arg.SkipWhitespace; context.arg.String(filename);
  19. DNS.HostByName(hostname, ipAdr, res);
  20. IF (res = DNS.Ok) THEN
  21. IP.AdrToStr(ipAdr, adrStr);
  22. NEW(connection);
  23. connection.Open(TCP.NilPort, ipAdr, port, res);
  24. IF (res = TCP.Ok) THEN
  25. NEW(writer, connection.Send, BufferSize);
  26. context.out.String("Connected to "); context.out.String(adrStr); context.out.String(":"); context.out.Int(port, 0);
  27. context.out.Ln;
  28. file := Files.Old(filename);
  29. IF (file # NIL) THEN
  30. context.out.String("Sending file "); context.out.String(filename); context.out.String(" ... ");
  31. NEW(buffer, BufferSize);
  32. NEW(reader, file, 0);
  33. offset := 0;
  34. reader.Bytes(buffer^, offset, BufferSize, len);
  35. WHILE (len > 0) DO
  36. writer.Bytes(buffer^, 0, len);
  37. INC(offset, BufferSize);
  38. reader.Bytes(buffer^, 0, BufferSize, len);
  39. END;
  40. writer.Update;
  41. context.out.String("done."); context.out.Ln;
  42. ELSE
  43. context.error.String("Could not open file "); context.error.String(filename); context.error.Ln;
  44. END;
  45. connection.Close;
  46. ELSE
  47. context.error.String("Could not open connection to server "); context.error.String(hostname);
  48. context.error.String(" ("); context.error.String(adrStr); context.error.String(":"); context.error.Int(port, 0);
  49. context.error.String("), res: "); context.error.Int(res, 0); context.error.Ln;
  50. END;
  51. ELSE
  52. context.error.String("Could not resolve hostname '"); context.error.String(hostname);
  53. context.error.String("', res: "); context.error.Int(res, 0); context.error.Ln;
  54. END;
  55. END SendFile;
  56. END TCPTools.
  57. TCPTools.SendFile 129.132.134.254 9100 test.ps ~
  58. System.Free TCPTools ~