TcpClient.java 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. /*
  2. * To change this license header, choose License Headers in Project Properties.
  3. * To change this template file, choose Tools | Templates
  4. * and open the template in the editor.
  5. */
  6. package rsx.tcp;
  7. import java.io.BufferedReader;
  8. import java.io.DataOutputStream;
  9. import java.io.IOException;
  10. import java.io.InputStreamReader;
  11. import java.io.PrintWriter;
  12. import java.net.InetAddress;
  13. import java.net.Socket;
  14. import java.net.UnknownHostException;
  15. /**
  16. *
  17. * @author loquicom
  18. */
  19. public class TcpClient {
  20. protected InetAddress adr;
  21. protected int port;
  22. protected Socket socket;
  23. protected BufferedReader input;
  24. protected PrintWriter output;
  25. /* --- Constructeurs --- */
  26. public TcpClient(String ip, int port) throws UnknownHostException{
  27. this.adr = InetAddress.getByName(ip);
  28. this.port = port;
  29. }
  30. public TcpClient(InetAddress adr, int port){
  31. this.adr = adr;
  32. this.port = port;
  33. }
  34. /* --- Methodes --- */
  35. public boolean connect(){
  36. try {
  37. this.socket = new Socket(this.adr, this.port);
  38. this.input = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
  39. //this.output = new PrintWriter(new BufferedWriter(new OutputStreamWriter(this.socket.getOutputStream())));
  40. this.output = new PrintWriter(this.socket.getOutputStream());
  41. } catch (IOException ex) {
  42. System.err.println("Impossible de se connecter au serveur : " + ex.getMessage());
  43. return false;
  44. }
  45. return true;
  46. }
  47. public boolean send(String msg){
  48. output.print(msg);
  49. output.flush();
  50. return true;
  51. }
  52. public String receive(){
  53. try {
  54. return input.readLine();
  55. } catch (IOException ex) {
  56. System.err.println("Impossible de lire : " + ex.getMessage());
  57. return null;
  58. }
  59. }
  60. public boolean close(){
  61. try {
  62. input.close();
  63. output.close();
  64. socket.close();
  65. } catch (IOException ex) {
  66. System.err.println("Impossible de de fermer le client : " + ex.getMessage());
  67. return false;
  68. }
  69. return true;
  70. }
  71. /* --- Getter/Setter --- */
  72. public InetAddress getAdr() {
  73. return adr;
  74. }
  75. public void setAdr(InetAddress adr) {
  76. this.adr = adr;
  77. }
  78. public int getPort() {
  79. return port;
  80. }
  81. public void setPort(int port) {
  82. this.port = port;
  83. }
  84. }