Akash Sethi
Akash Sethi

Reputation: 2294

how to read tcp stream using scala

I have a java jar that generates the tcp stream on particular port.

I cam run the using java command like java -jar runner.jar and this start producing the stream of message on port 8888.

When I do nc -l 8888 I can see the messages.

I want to read this stream using scala and another framework or tool like akka, akka-stream.

Can anyone help me understand the best tool, framework or any other technique to read this tcp stream.

I tried using akka stream with following code :-

implicit val system = ActorSystem()
    implicit val mater = ActorMaterializer() val ss  = Tcp().outgoingConnection("127.0.0.1", 8888)
      .to(Sink.foreach(println(_)))
    Source.empty.to(ss).run()

I also tried

Tcp().outgoingConnection(new InetSocketAddress("127.0.0.1", 8888))
        .runWith(Source.maybe[ByteString], Sink.foreach(bs => println(bs.utf8String)))

This doesn't work.

I only need to read the messages and process on my own.

Thanks

Upvotes: 1

Views: 381

Answers (1)

Łukasz Gawron
Łukasz Gawron

Reputation: 917

As I understand you want to setup TCP server, here is example of TCP Echo using akka streams

def server(system: ActorSystem, address: String, port: Int): Unit = {
implicit val sys = system
import system.dispatcher
implicit val materializer = ActorMaterializer()

val handler = Sink.foreach[Tcp.IncomingConnection] { conn =>
  println("Client connected from: " + conn.remoteAddress)
  conn handleWith Flow[ByteString]
}

val connections = Tcp().bind(address, port)
val binding = connections.to(handler).run()

binding.onComplete {
  case Success(b) =>
    println("Server started, listening on: " + b.localAddress)
  case Failure(e) =>
    println(s"Server could not bind to $address:$port: ${e.getMessage}")
    system.terminate()
}

}

Upvotes: 1

Related Questions