Advertisement
Guest User

TCPConnection

a guest
Jul 17th, 2019
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.18 KB | None | 0 0
  1. package chat.network;
  2.  
  3. import java.io.*;
  4. import java.net.Socket;
  5. import java.nio.charset.Charset;
  6.  
  7. public class TCPConnection {
  8.  
  9. private final Socket socket;
  10. private final Thread rxThread;
  11. private final TCPConnectionListener eventListener;
  12. private final BufferedReader in;
  13. private final BufferedWriter out;
  14.  
  15. public TCPConnection(TCPConnectionListener eventListener, String ipAddr, int port) throws IOException{
  16. this(eventListener, new Socket(ipAddr, port));
  17. }
  18.  
  19. public TCPConnection(TCPConnectionListener eventListener, Socket socket) throws IOException{
  20. this.socket = socket;
  21. in = new BufferedReader(new InputStreamReader(socket.getInputStream(), Charset.forName("UTF-8")));
  22. out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), Charset.forName("UTF-8")));
  23. rxThread = new Thread(new Runnable() {
  24. @Override
  25. public void run() {
  26. try {
  27. eventListener.onCOnnectionReady(TCPConnection.this);
  28. while(!rxThread.isInterrupted()){
  29. eventListener.onRecieveString(TCPConnection.this, in.readLine());
  30. }
  31. String msg = in.readLine();
  32. } catch (IOException e){
  33. eventListener.onException(TCPConnection.this, e);
  34. } finally {
  35. eventListener.onDisconnect(TCPConnection.this);
  36. }
  37. }
  38. });
  39. rxThread.start();
  40.  
  41. }
  42. public synchronized void sendString(String value){
  43. try{
  44. out.write(value + "\r\n");
  45. out.flush();
  46. } catch(IOException e){
  47. eventListener.onException(TCPConnection.this, e);
  48. disconnect();
  49. }
  50. }
  51. public synchronized void disconnect(){
  52. rxThread.interrupt();
  53. try {
  54. socket.close();
  55. } catch (IOException e){
  56. eventListener.onException(TCPConnection.this, e);
  57. }
  58. }
  59. @Override
  60. public String toString(){
  61. return "TCPConnection: " + socket.getInetAddress() + ": " + socket.getPort();
  62. }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement