我正在尝试制作一个Android应用程序,它包含使用消息代理的设备之间的通信(简单地传递固定消息)(我选择了RabbitMQ)。几天来,我一直在努力建立连接。客户端还没准备好,我想先让我的服务器工作。
这是我的一段代码:
public class HomeView extends Fragment {
ImageButton imageButton;
private String mText;
private View mContent;
public HomeView() { }
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
mContent = inflater.inflate(R.layout.home_view, container, false);
configureImageButton();
setupServer();
return mContent;
}
private void configureImageButton() {
imageButton = (ImageButton) getmContent().findViewById(R.id.imageButton);
ImageButton.OnClickListener listener = new ImageButton.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getActivity(), "message", Toast.LENGTH_SHORT).show();
// message to server will be sent here
}
};
imageButton.setOnClickListener(listener);
}
Thread setupServerThread;
ConnectionFactory factory = new ConnectionFactory();
void setupServer() {
setupServerThread = new Thread(new Runnable() {
@Override
public void run() {
while(true) {
try {
Connection connection = null;
factory.setUri("amqp://guest:guest@localhost:5672/");
connection = factory.newConnection();
final Channel channel = connection.createChannel();
channel.queueDeclare(RPC_QUEUE_NAME, true, false, false, null);
channel.basicQos(1);
Consumer consumer = new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
AMQP.BasicProperties replyProps = new AMQP.BasicProperties
.Builder()
.correlationId(properties.getCorrelationId())
.build();
String response = "";
try {
String message = new String(body,"UTF-8");
int n = Integer.parseInt(message);
response += n.toString());
}
catch (RuntimeException e){
e.printStackTrace();
}
finally {
channel.basicPublish( "", properties.getReplyTo(), replyProps, response.getBytes("UTF-8"));
channel.basicAck(envelope.getDeliveryTag(), false);
}
}
};
channel.basicConsume(RPC_QUEUE_NAME, false, consumer);
while(true) {
try {
Thread.sleep(100);
} catch (InterruptedException _ignore) {}
}
} catch (Exception e1) {
e1.printStackTrace();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
break;
}
}
}
}
});
setupServerThread.start();
}
}
问题是在这一行之后:
connection = factory.newConnection();
连接为null并抛出“连接被拒绝”异常。 当我运行与简单Java程序相同的代码时,一切正常。
请看一下,我非常感谢任何帮助!