我有一个案例场景,我有一个流生成器客户端,它生成多个流,合并它们并将其发送到套接字,我希望Flink程序听取它作为服务器即可。我们知道必须首先启动服务器,以便它可以侦听客户端请求。我尝试使用下面给出的代码
来做同样的事情 public static void main(String[] args) throws Exception {
//setting the envrionment variable as StreamExecutionEnvironment
StreamExecutionEnvironment environment = StreamExecutionEnvironment.getExecutionEnvironment();
environment.setParallelism(1);
DataStream<String> stream1 = environment.socketTextStream("localhost", 9000);
stream1.print();
//start the execution
environment.execute(" Started the execution ");
}// main
作为客户端的流生成器代码如下所示
DataStream<Event> stream1 = envrionment
.addSource(new EventGenerator(2,60,1,1,100, 200 ))
.name("stream 1")
.setParallelism(parallelism_for_stream_rr);
DataStream<Event> stream2 = envrionment
.addSource(new EventGenerator(3,60,1,2,10, 20 ))
.name("stream 2")
.setParallelism(parallelism_for_stream_rr);
DataStream<Event> stream3 = envrionment
.addSource(new EventGenerator(5,60,1,3,30, 40 ))
.name("stream 3")
.setParallelism(parallelism_for_stream_rr);
DataStream<Event> merged = stream1.union(stream2,stream3);
merged.print();
// sending data to Mobile Cep via socket
merged.map(new MapFunction<Event, String>() {
@Override
public String map(Event event) throws Exception {
String tuple = event.toString();
return tuple + "\n";
}
}).writeToSocket("localhost", 9000, new SimpleStringSchema() );
问题1:问题是客户端代码仅在我启动Netcat服务器时有效,但Netcat服务器不会转发数据流。如果Netcat服务器未启动,则客户端代码表示无法建立连接< / p>
问题#2:如果Netcat服务器未启动,则Flink程序不会执行
Caused by: java.net.ConnectException: Connection refused (Connection refused)
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
我知道一个可能的解决方案是在Flink程序中生成流,但我想通过套接字接收流。
先谢谢〜
答案 0 :(得分:2)
Flink的套接字源及其接收器都没有启动TCP服务器并等待传入连接。它们都是连接已启动的TCP服务器的客户端。这也是为什么你必须在启动工作之前启动netcat
的原因。如果你想写入和读取套接字,那么你必须编写一个TCP服务器,它可以缓冲传入的数据,并在客户端连接它时转发它们。