我正在尝试创建一个套接字应用程序,将一些数据从另一个应用程序发送到客户端。访问数据的代码使用抽象类。
SubscriptionAdapter listener = new SubscriptionAdapter() {
@Override
public void onSubscriptionData(SubscriptionData data) {
for (AnyJson json : data.getMessages()) {
System.out.println(json.toString());
}
}
};
SubscriptionAdapter()的机制有点奇怪。 onSubscriptionData被反复调用,for循环将返回1到多个记录。以下是一些示例输出:
Yup
Got message: {"type":"lightning","location":{"coords":{"lon":18.509391,"lat":38.7581},"polarity":0}}
Yup
Got message: {"type":"lightning","location":{"coords":{"lon":18.504115,"lat":38.765076},"polarity":0}}
Got message: {"type":"lightning","location":{"coords":{"lon":18.494549,"lat":38.778813},"polarity":0}}
“Yup”是我在for循环上面放置的一行调试代码,用于确认类的功能。
以下是我正在使用的示例套接字服务器:
import java.net.*;
import java.io.*;
public class Server {
/**
* @param args the command line arguments
*/
public static void main(String[] args) //throws Exception
{
try
{
ServerSocket serverSocket = new ServerSocket(9090);
System.out.println("Waiting for clients...");
Socket socket = serverSocket.accept();
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println("Hello client!");
out.close();
socket.close();
serverSocket.close();
} catch (Exception e)
{
System.out.println(e.toString());
}
}
}
目标是让System.out.println(json.toString());
输出到套接字连接。但是,我一直在考虑范围问题。
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
会超出范围。我已经在那里待了几个小时,此时,我可以使用一些建议。
按要求更新。以下是完整代码:
import com.satori.rtm.*;
import com.satori.rtm.model.*;
public class SubscribeToWeatherChannel {
static final String endpoint = [end point];
static final String appkey = [app key];
static final String channel = "full-weather";
public static void main(String[] args) throws InterruptedException {
final RtmClient client = new RtmClientBuilder(endpoint, appkey)
.setListener(new RtmClientAdapter() {
@Override
public void onEnterConnected(RtmClient client) {
System.out.println("Connected to Satori RTM!");
}
})
.build();
SubscriptionAdapter listener = new SubscriptionAdapter() {
@Override
public void onSubscriptionData(SubscriptionData data) {
for (AnyJson json : data.getMessages()) {
System.out.println(json.toString());
}
}
};
client.createSubscription(channel, SubscriptionMode.SIMPLE, listener);
client.start();
}
}
答案 0 :(得分:0)
实际上归功于Kayaman的解决方案。
不要创建抽象类的匿名实例。创建一个 适当的类扩展了SubscriptionAdapter,然后你可以传递它 PrintWriters或您需要的任何其他东西。
import com.satori.rtm.*;
import com.satori.rtm.model.*;
import java.net.*;
import java.io.*;
public class SpecificSubscriptionAdapter extends SubscriptionAdapter {
public static PrintWriter out;
public SpecificSubscriptionAdapter(PrintWriter out){
this.out = out;
}
@Override
public void onSubscriptionData(SubscriptionData data) {
for (AnyJson json : data.getMessages()) {
out.println(json.toString());
}
}
}