| Line | |
|---|
| 1 | package com.joelpm.bidiMessages.client;
|
|---|
| 2 |
|
|---|
| 3 | import java.util.concurrent.BlockingQueue;
|
|---|
| 4 | import java.util.concurrent.LinkedBlockingQueue;
|
|---|
| 5 |
|
|---|
| 6 | import org.apache.thrift.TException;
|
|---|
| 7 | import org.apache.thrift.protocol.TProtocol;
|
|---|
| 8 | import com.joelpm.bidiMessages.generated.Message;
|
|---|
| 9 | import com.joelpm.bidiMessages.generated.MessageService;
|
|---|
| 10 |
|
|---|
| 11 | /**
|
|---|
| 12 | * The class responsible for sending messages to the server.
|
|---|
| 13 | *
|
|---|
| 14 | * @author Joel Meyer
|
|---|
| 15 | */
|
|---|
| 16 | public class MessageSender extends ConnectionRequiredRunnable {
|
|---|
| 17 | private final MessageService.Client client;
|
|---|
| 18 | private final BlockingQueue<Message> msgSendQueue;
|
|---|
| 19 |
|
|---|
| 20 | public MessageSender(
|
|---|
| 21 | TProtocol protocol,
|
|---|
| 22 | ConnectionStatusMonitor connectionMonitor) {
|
|---|
| 23 | super(connectionMonitor, "Message Sender");
|
|---|
| 24 | this.client = new MessageService.Client(protocol);
|
|---|
| 25 | this.msgSendQueue = new LinkedBlockingQueue<Message>();
|
|---|
| 26 | }
|
|---|
| 27 |
|
|---|
| 28 | public void send(Message msg) {
|
|---|
| 29 | msgSendQueue.add(msg);
|
|---|
| 30 | }
|
|---|
| 31 |
|
|---|
| 32 | @Override
|
|---|
| 33 | public void run() {
|
|---|
| 34 | connectWait();
|
|---|
| 35 | while (true) {
|
|---|
| 36 | try {
|
|---|
| 37 | Message msg = msgSendQueue.take();
|
|---|
| 38 | try {
|
|---|
| 39 | client.sendMessage(msg);
|
|---|
| 40 | } catch (TException e) {
|
|---|
| 41 | // The message isn't lost, but it could end up being sent out of
|
|---|
| 42 | // order - not ideal.
|
|---|
| 43 | msgSendQueue.add(msg);
|
|---|
| 44 | disconnected();
|
|---|
| 45 | }
|
|---|
| 46 | } catch (InterruptedException e) {
|
|---|
| 47 | // Thread will be interrupted if connection is lost, we should wait
|
|---|
| 48 | // for reconnection if that happens.
|
|---|
| 49 | connectWait();
|
|---|
| 50 | }
|
|---|
| 51 | }
|
|---|
| 52 | }
|
|---|
| 53 | }
|
|---|
| 54 |
|
|---|
Note:
See
TracBrowser
for help on using the repository browser.