Reputation: 1310
I'm trying to realize FS2 client application with GUI on FS2 library.
Realization includes 2 steps:
User enter host and port in fields of Panel:
If request and response success, we see "data send successfully" in this Panel
Client code is:
def connect[F[_] : Temporal : Network](address: SocketAddress[Host]): Stream[F, Socket[F]] = {
Stream.resource(Network[F].client(address))
.handleErrorWith {
case _: ConnectException =>
connect(address).delayBy(5.seconds)
}
}
def client[F[_]: Temporal: Console: Network](host: String, port: Int): Stream[F, Unit] =
connect(SocketAddress(Host.fromString(host).getOrElse(host"localhost"), Port.fromInt(port).getOrElse(port"5555")))
.flatMap { socket =>
// request and response in Stream //
}
GUI code:
def createAndShowGUI(): JFrame = {
val frame = new JFrame("FS2 + Swing Example")
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
frame.setSize(400, 200)
val panel = new JPanel()
frame.add(panel)
val hostLabel = new JLabel("Host:")
val hostField = new JTextField(20)
val portLabel = new JLabel("Port:")
val portField = new JTextField(20)
val resultLabel = new JLabel("Response will appear here")
val connectButton = new JButton("Connect")
connectButton.addActionListener(new ActionListener {
override def actionPerformed(e: ActionEvent): Unit = {
val host = hostField.getText
val port = portField.getText.toInt
client[IO](host, port).compile.drain.unsafeRunAsync {
case Right(_) => SwingUtilities.invokeLater(() => resultLabel.setText("data send successfully"))
case Left(ex) => SwingUtilities.invokeLater(() => resultLabel.setText(s"Error: ${ex.getMessage}"))
}
}
})
panel.add(hostLabel)
panel.add(hostField)
panel.add(portLabel)
panel.add(portField)
panel.add(connectButton)
panel.add(resultLabel)
frame.setVisible(true)
}
Method is invoked:
override def run: IO[Unit] = IO {
SwingUtilities.invokeLater(() => {createAndShowGUI()})
}
Realisation is interrupted at this line
.flatMap { socket =>
of method client[F[_]: Temporal: Console: Network]:
Non-daemon threads currently preventing JVM termination: - 23:
Thread[DestroyJavaVM,5,main]
- - 20: Thread[AWT-EventQueue-0,6,main]
- - 19: Thread[AWT-Shutdown,5,system]
Upvotes: 1
Views: 32