LocalSocket.cpp 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /*
  2. * Copyright (c) Contributors to the Open 3D Engine Project.
  3. * For complete copyright and license terms please see the LICENSE at the root of this distribution.
  4. *
  5. * SPDX-License-Identifier: Apache-2.0 OR MIT
  6. *
  7. */
  8. #include <AtomToolsFramework/Communication/LocalSocket.h>
  9. #include <AzCore/Debug/Trace.h>
  10. #include <QByteArray>
  11. #include <QString>
  12. namespace AtomToolsFramework
  13. {
  14. LocalSocket::LocalSocket()
  15. {
  16. }
  17. LocalSocket::~LocalSocket()
  18. {
  19. Disconnect();
  20. }
  21. bool LocalSocket::Connect(const QString& serverName)
  22. {
  23. Disconnect();
  24. m_serverName = serverName;
  25. AZ_TracePrintf("AtomToolsFramework::LocalSocket", "Connecting to: %s\n", m_serverName.toUtf8().constData());
  26. m_socket.connectToServer(m_serverName);
  27. if (IsConnected())
  28. {
  29. AZ_TracePrintf("AtomToolsFramework::LocalSocket", "Waiting for connection to: %s\n", m_serverName.toUtf8().constData());
  30. if (m_socket.waitForConnected())
  31. {
  32. AZ_TracePrintf("AtomToolsFramework::LocalSocket", "Connected to: %s\n", m_serverName.toUtf8().constData());
  33. return true;
  34. }
  35. }
  36. AZ_TracePrintf("AtomToolsFramework::LocalSocket", "Connecting failed: %s\n", m_serverName.toUtf8().constData());
  37. Disconnect();
  38. return false;
  39. }
  40. void LocalSocket::Disconnect()
  41. {
  42. if (IsConnected())
  43. {
  44. AZ_TracePrintf("AtomToolsFramework::LocalSocket", "Disconnecting from: %s\n", m_serverName.toUtf8().constData());
  45. m_socket.disconnectFromServer();
  46. m_socket.waitForDisconnected();
  47. AZ_TracePrintf("AtomToolsFramework::LocalSocket", "Closing socket\n");
  48. m_socket.close();
  49. }
  50. }
  51. bool LocalSocket::IsConnected() const
  52. {
  53. return m_socket.isOpen();
  54. }
  55. bool LocalSocket::Send(const QByteArray& buffer)
  56. {
  57. if (IsConnected())
  58. {
  59. AZ_TracePrintf("AtomToolsFramework::LocalSocket", "Sending data to: %s\n", m_serverName.toUtf8().constData());
  60. m_socket.write(buffer);
  61. AZ_TracePrintf("AtomToolsFramework::LocalSocket", "Waiting for write to: %s\n", m_serverName.toUtf8().constData());
  62. m_socket.waitForBytesWritten();
  63. return true;
  64. }
  65. return false;
  66. }
  67. } // namespace AtomToolsFramework
  68. #include <AtomToolsFramework/Communication/moc_LocalSocket.cpp>