I have simple Vertx-based websocket chatting app. It consists of two parts MsgServerVerticle and MsgClientVerticle (source code below). So, if I am instantiating one server and only one client it looks like working normally. After second client connects, server starts trying to announce it to other clients. And things gonna weird. Log says that netty backed are encoding-decoding websocket frames continuously in loop. There is no difference what type of frames I am using, binary or text, issues are the same.
log screenshot here
What's wrong?
MsgClientVerticle Source code:
private Logger L;
private String eBusTag;
private String backwardTag;
private String targetHost;
private int port;
private String id;
private String path;
private EventBus eBus;
private HttpClient client;
public MsgClientVerticle(String eBusTag, String targetHost, int port, String path, String id, String backwardTag) {
this.eBusTag = eBusTag;
this.targetHost = targetHost;
this.path = path;
this.port = port;
this.id = id;
this.backwardTag = backwardTag;
L = LoggerFactory.getLogger(eBusTag);
}
#Override
public void start(Future<Void> startFuture) throws Exception {
L.info("Initializing client connection to " + targetHost + ":" + port + path);
eBus = vertx.eventBus();
try {
client = vertx.createHttpClient();
client.websocket(port, targetHost, path, webSock -> {
L.info("Connected to " + targetHost + ":" + port + "/" + path);
eBus.publish(backwardTag, Utils.msg("Connected"));
webSock.binaryMessageHandler(buf -> {
eBus.publish(backwardTag, Utils.bufToJson(buf));
});
eBus.consumer(eBusTag).handler(msg -> {
JsonObject message = (JsonObject) msg.body();
webSock.writeBinaryMessage(Utils.jsonToBuf(message));
});
});
} catch (NullPointerException e) {
L.error("Null Pointer: " + e.getLocalizedMessage());
e.printStackTrace();
}
startFuture.complete();
}
#Override
public void stop(Future<Void> stopFuture) throws Exception {
L.info("Connection to " + targetHost + ":" + port + "/" + path + " closed");
client.close();
stopFuture.complete();
}
And MsgServerVerticle source:
private Logger L;
private String path;
private int port;
private String eBusTag;
private String backwardTag;
private HttpServer server;
private EventBus eBus;
private Set<ServerWebSocket> conns;
public MsgServerVerticle(int port, String eBusTag, String backwardTag) {
this.port = port;
this.eBusTag = eBusTag;
this.backwardTag = backwardTag;
conns = new ConcurrentSet<>();
path = eBusTag;
L = LoggerFactory.getLogger(eBusTag);
}
#Override
public void start(Future<Void> startFuture) throws Exception {
eBus = vertx.eventBus();
L.info("Initializing server instance at port " + port);
server = vertx.createHttpServer();
server.websocketHandler(webSock -> {
if (!webSock.path().equals(path)) {
webSock.reject();
} else {
conns.add(webSock);
conns.forEach(sock -> {
if (sock != webSock) {
sock.writeBinaryMessage(Utils.jsonToBuf(Utils.msg("SERVER: new client " + webSock.remoteAddress().toString())));
}
});
eBus.publish(backwardTag, Utils.msg("SERVER: new client " + webSock.remoteAddress().toString()));
webSock.binaryMessageHandler(buf -> {
JsonObject msg = Utils.bufToJson(buf);
conns.forEach(sock -> {
if (sock != webSock) {
sock.writeBinaryMessage(buf);
}
});
eBus.publish(backwardTag, msg);
});
}
});
server.listen(port);
startFuture.complete();
}
#Override
public void stop(Future<Void> stopFuture) throws Exception {
conns.forEach(sock -> {
sock.writeFinalTextFrame("Server is shutting down...");
});
server.close();
stopFuture.complete();
}
I wasn't able to reproduce your original problem. But I had to make a few changes in the first place to test it.
One change is in initialization of your server:
this.path = "/" + eBusTag;
Otherwise this check will always fail:
if (!webSock.path().equals(this.path)) {
Since websock.path() will always start with /, hence /anything=/=anything
Second, please take a look how I initialized the clients, and check if you do the same:
final Vertx vertx = Vertx.vertx();
vertx.deployVerticle(new MsgServerVerticle(8080,
"ebus",
"back"), new DeploymentOptions().setWorker(true), (r) -> {
vertx.deployVerticle(new MsgClientVerticle("ebus",
"127.0.0.1",
8080,
"/ebus",
"a",
"back"), new DeploymentOptions().setWorker(true), (r2) -> {
vertx.deployVerticle(new MsgClientVerticle("ebus",
"127.0.0.1",
8080,
"/ebus",
"b",
"back"), new DeploymentOptions().setWorker(true), (r3) -> {
System.out.println("Done");
});
});
});
And third, as far as I could understand, your Utils class is something you implemented. My implementation looks as follows:
public class Utils {
public static Buffer jsonToBuf(final JsonObject message) {
return message.toBuffer();
}
public static JsonObject bufToJson(final Buffer buf) {
return buf.toJsonObject();
}
public static JsonObject msg(final String msg) {
return new JsonObject("{\"value\":\"" + msg + "\"}");
}
}
Hope that helps pinpoint your problem.
Related
I'm currently trying to have my device (program) show up as a mock chromecast on the network. The application itself can see the Mock-Caster as a chromecast but if i try searching for it using Youtube or any other sender app, the "Mock-Caster" does not appear in the list.
I registered a service on jmDNS with all the criteria that would be available on an actual chromecast as well.
Is there something that I am missing or getting wrong?
Here's what I have so far.
public void postConstruct() throws Exception {
InetAddress discoveryInterface = InetAddress.getByName("192.168.1.1");
CAST_DEVICE_MONITOR.startDiscovery(discoveryInterface, "Mock-Server");
CAST_DEVICE_MONITOR.registerListener(new DeviceDiscoveryListener() {
#Override
public void deviceDiscovered(CastDevice castDevice) {
System.out.println("New chrome cast detected: " + castDevice);
}
#Override
public void deviceRemoved(CastDevice castDevice) {
System.out.println("New chrome cast detected: " + castDevice);
}
});
JmDNS jmdns = JmDNS.create(discoveryInterface, "Mock-Server");
final String name = "Mock-Caster";
final String id = UUID.randomUUID().toString();
// Register a service
HashMap<String, String> properties = new HashMap<>();
//values scraped from chromecast or another java project
properties.put("sf", "1");
properties.put("id", id);
properties.put("md", name);
properties.put("fd", name);
properties.put("s#", "1");
properties.put("ff", "0");
properties.put("ci", "1");
properties.put("c#", Integer.toString(1));
properties.put("pv", "1.1");
properties.put("cd", "E465315D08CFDEF2742E1264D78F6035");
properties.put("rm", "ED724E435DA8115C");
properties.put("ve", "05");
properties.put("ic", "/setup/icon.png");
properties.put("ca", "201221");
properties.put("st", "0");
properties.put("bs", "FA8FCA771881");
properties.put("nf", "1");
properties.put("rs", "");
ServiceInfo serviceInfo = ServiceInfo.create("_googlecast._tcp.local.", name, 8009, 1, 1, properties);
jmdns.registerService(serviceInfo);
}
//This is where i know that the mock-caster is registered and available
#Bean
public IntegrationFlow tcpServer() throws Exception {
TcpNioServerConnectionFactory factory = new TcpNioServerConnectionFactory(8009);
DefaultTcpSSLContextSupport defaultTcpSSLContextSupport = new DefaultTcpSSLContextSupport(keystore, keystore, password, password);
defaultTcpSSLContextSupport.setProtocol("TLS");
factory.setTcpNioConnectionSupport(new DefaultTcpNioSSLConnectionSupport(defaultTcpSSLContextSupport));
factory.setTcpSocketSupport(new DefaultTcpSocketSupport(false));
factory.setDeserializer(TcpCodecs.lengthHeader4());
factory.setSerializer(TcpCodecs.lengthHeader4());
TcpInboundGatewaySpec inboundGateway = Tcp.inboundGateway(factory);
return IntegrationFlows
.from(inboundGateway)
.handle(message -> {
String ip_address = message.getHeaders().get("ip_address").toString();
if(ip_address.equalsIgnoreCase("192.168.1.1")) {
System.out.println("Self IP Address received");
System.out.println("Payload: " + message.getPayload());
System.out.println("MessageHeaders: " + message.getHeaders());
}else{
System.out.println("Other IP address received: " + ip_address);
}
})
.get();
}
//Mock-Caster detected here
#Scheduled(fixedRate = 15000)
public void checkCasters() throws Exception {
Set<CastDevice> casters = CAST_DEVICE_MONITOR.getCastDevices();
System.out.println("Current CCs: " + casters.size());
for (CastDevice device : casters) {
System.out.println("CC (" + device.getDisplayName() + ")");
var receiver = new CastEvent.CastEventListener() {
#Override
public void onEvent(#Nonnull CastEvent<?> castEvent) {
System.out.println("Event: " + castEvent);
}
};
var appId = DEFAULT_MEDIA_RECEIVER_APP;
try {
if (!device.isConnected()) {
device.connect();
}
device.addEventListener(receiver);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
device.removeEventListener(receiver);
device.disconnect();
}
}
MessageCreator: Encapsulate and resolve ports and device unique identifiers.
public class MessageCreator {
private static final String HEADER_PORT = "to port:";
private static final String HEADER_SN = "My sn:";
public static String buildWithPort(int port) {
return HEADER_PORT + port;
}
public static int parsePort(String data) {
if (data.startsWith(HEADER_PORT)) {
return Integer.parseInt(data.substring(HEADER_PORT.length()));
}
return -1;
}
public static String buildWithSn(String sn) {
return HEADER_SN + sn;
}
public static String parseSn(String data) {
if (data.startsWith(HEADER_SN)) {
return data.substring(HEADER_SN.length());
}
return null;
}
}
UdpProvider: Loop to listen to a specific port, then parse the received data, determine whether the data conforms to the predetermined format, get the sender's response port from it, and respond with the uniquely identified UUID value to the UDP searcher.
public class UdpProvider {
public static void main(String[] args) throws IOException {
String sn = UUID.randomUUID().toString();
Provider provider = new Provider(sn);
provider.start();
// Warning: Result of 'InputStream.read()' is ignored
System.in.read();
provider.exit();
}
private static class Provider extends Thread {
private DatagramSocket ds = null;
private boolean done = false;
private final String sn;
public Provider(String sn) {
super();
this.sn = sn;
}
#Override
public void run() {
super.run();
try {
ds = new DatagramSocket(20000);
while (!done) {
final byte[] buf = new byte[512];
DatagramPacket receivePak = new DatagramPacket(buf, buf.length);
ds.receive(receivePak);
String ip = receivePak.getAddress().getHostAddress();
int port = receivePak.getPort();
byte[] receivePakData = receivePak.getData();
String receiveData = new String(receivePakData, 0, /*receivePakData.length*/receivePak.getLength());
System.out.println("received from -> ip: " + ip + ", port: " + port + ", data: " + receiveData);
int responsePort = MessageCreator.parsePort(receiveData.trim());
if (responsePort != -1) {
String responseData = MessageCreator.buildWithSn(sn);
byte[] bytes = responseData.getBytes(StandardCharsets.UTF_8);
DatagramPacket responsePak = new DatagramPacket(bytes, bytes.length,
/*InetAddress.getLocalHost()*/
receivePak.getAddress(),
responsePort);
ds.send(responsePak);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
close();
}
}
public void exit() {
done = true;
close();
}
public void close() {
if (ds != null) {
ds.close();
ds = null;
}
}
}
}
UdpSearcher: Listening to a specific port and sending a LAN broadcast, sending a broadcast sets the listening port in the data, so you need to turn on listening first to finish before you can send a broadcast, and once you receive the response data, you can parse the device information
public class UdpSearcher {
private static final int LISTENER_PORT = 30000;
public static void main(String[] args) throws IOException, InterruptedException {
Listener listener = listen();
sendBroadcast();
// Warning: Result of 'InputStream.read()' is ignored
System.in.read();
List<Device> deviceList = listener.getDevicesAndClose();
for (Device device : deviceList) {
System.out.println(device);
}
}
public static void sendBroadcast() throws IOException {
DatagramSocket ds = new DatagramSocket();
String sendData = MessageCreator.buildWithPort(LISTENER_PORT);
byte[] sendDataBytes = sendData.getBytes(StandardCharsets.UTF_8);
DatagramPacket sendPak = new DatagramPacket(sendDataBytes, sendDataBytes.length);
sendPak.setAddress(InetAddress.getByName("255.255.255.255"));
sendPak.setPort(20000);
ds.send(sendPak);
ds.close();
}
public static Listener listen() throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(1);
Listener listener = new Listener(LISTENER_PORT, countDownLatch);
listener.start();
countDownLatch.await();
return listener;
}
private static class Listener extends Thread {
private final int listenPort;
private DatagramSocket ds = null;
private boolean done = false;
private final CountDownLatch countDownLatch;
private List<Device> devices = new ArrayList<>();
public Listener(int listenPort, CountDownLatch countDownLatch) {
super();
this.listenPort = listenPort;
this.countDownLatch = countDownLatch;
}
#Override
public void run() {
super.run();
countDownLatch.countDown();
try {
ds = new DatagramSocket(listenPort);
while (!done) {
final byte[] buf = new byte[512];
DatagramPacket receivePak = new DatagramPacket(buf, buf.length);
ds.receive(receivePak);
String ip = receivePak.getAddress().getHostAddress();
int port = receivePak.getPort();
byte[] data = receivePak.getData();
String receiveData = new String(data, 0, /*data.length*/receivePak.getLength());
String sn = MessageCreator.parseSn(receiveData);
System.out.println("received from -> ip: " + ip + ", port: " + port + ", data: " + receiveData);
if (sn != null) {
Device device = new Device(ip, port, sn);
devices.add(device);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
close();
}
}
public void close() {
if (ds != null) {
ds.close();
ds = null;
}
}
public List<Device> getDevicesAndClose() {
done = true;
close();
return devices;
}
}
private static class Device {
private String ip;
private int port;
private String sn;
public Device(String ip, int port, String sn) {
this.ip = ip;
this.port = port;
this.sn = sn;
}
#Override
public String toString() {
return "Device{" +
"ip='" + ip + '\'' +
", port=" + port +
", sn='" + sn + '\'' +
'}';
}
}
}
UdpProvider and UdpSearcher worked fine and printed corrresponding data until I input a char sequence from keyboard follwed by pressing Enter key on each console window, both threw an exception on this line ds.receive(receivePak); :
I am trying to restrict the amount of clients on my server,so i just sending message from my server when it is full and print it in my client by ending process for him.But as i use multiple threads i cant stop my writeMessage thread
Tried AtomicBoolean,but i didnt work
public class Client {
private static final Logger LOGGER = LogManager.getLogger();
private BufferedReader consoleReader;
private String name;
private String address;
private int port;
private Thread writeMessage, readMessage;
private ZonedDateTime zonedDateTime = ZonedDateTime.now(ZoneId.of("UTC"));
private LocalTime dTime = zonedDateTime.toLocalTime();
private Net net;
private AtomicBoolean running = new AtomicBoolean(true);
public Client(String address, int port) {
this.address = address;
this.port = port;
net = new Net(address, port);
consoleReader = new BufferedReader(new InputStreamReader(System.in));
printName();
readMessage();
writeMessage();
}
private void printName() {
System.out.println("Print your name:");
try {
name = consoleReader.readLine();
while (NameValidator.nameIsValid(name)) {
System.out.println("Name should contain more than 1 letter");
name = consoleReader.readLine();
}
net.send(name + "\n");
} catch (IOException e) {
LOGGER.error(e);
}
}
private void readMessage() {
readMessage = new Thread(() -> {
String str = net.receive();
while (net.isConnected()) {
if ("full".equals(str)) {
System.out.println("server is full");
running.set(false);
break;
} else {
System.out.println(str);
str = net.receive();
}
}
net.offService();
}, "readMessage");
readMessage.start();
}
private void writeMessage() {
writeMessage = new Thread(() -> {
while (running.get()) {
String userWord;
try {
String time = dTime.getHour() + ":" + dTime.getMinute() + ":" + dTime.getSecond();
userWord = consoleReader.readLine();
if (userWord.equals("quit")) {
net.send(userWord + "\n");
ClientAmountGenerator.decrement();
running.set(false);
} else {
net.send("(" + time + ") " + name + " says : " + userWord + "\n");
}
} catch (IOException e) {
LOGGER.error(e);
}
}
net.offService();
}, "writeMessage");
writeMessage.start();
}
}
I want to change running to "false",so the writeMessage thread wont work if it gets message "full" from the server
What I want to achieve
I want to get my string variable I am using as #DestinationVariable, called lobbyName, when socket disconnects using #EventListener on server side:
#Component
public class WebSocketEventListener {
private SimpMessageSendingOperations messagingTemplate;
public WebSocketEventListener(SimpMessageSendingOperations messagingTemplate) {
this.messagingTemplate = messagingTemplate;
}
#EventListener
public void handleWebSocketDisconnectListener(SessionDisconnectEvent event) {
//here I want to get my data
}
}
My problem
I have been trying to get lobbyName using SessionDisonnectEvent but I don't know how, when and where to put this lobbyName in order to have it in SessionDisconnectEvent.
What I have been trying
On Server Side:
#Controller
public class WebSocketController {
private final SimpMessagingTemplate template;
WebSocketController(SimpMessagingTemplate template) {
this.template = template;
}
public void pokeLobby(#DestinationVariable String lobbyName, SocketMessage message) {
// This didn't work
// Map<String, Object> headers = new HashMap<>();
// headers.put("lobbyName", lobbyName);
// this.template.convertAndSend("/lobby/"+lobbyName.toLowerCase(), message, headers);
this.template.convertAndSend("/lobby/"+lobbyName.toLowerCase(), message);
}
}
Is it possible to do on client side? :
connectToLobbyWebSocket(lobbyName: string): void {
const ws = new SockJS(this.addressStorage.apiAddress + '/socket');
this.stompClient = Stomp.over(ws);
// this.stompClient.debug = null;
const that = this;
this.stompClient.connect({}, function () {
that.stompClient.subscribe('/lobby/' + lobbyName, (message) => {
if (message.body) {
that.socketMessage.next(message.body); //client logic
}
});
});
}
EDIT (progress)
Since I can easily get sessionId on SessionDisconnectEvent I have decided to change sessionId (upon handshake) to something like playerId:lobbyName:uuid
I don't feel very comfortable with this solution so if you have any suggestions I am all ears.
const ws = new SockJS(this.addressStorage.apiAddress + '/socket', null, {
sessionId: function (): string {
return that.authManager.playerId + ':' + lobbyName + ':' + uuid();
}
});
You can send lobbyName in the body of the message as attribute and get it in the listner like this :
#EventListener
public void handleWebSocketDisconnectListener(SessionDisconnectEvent event) {
StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(event.getMessage());
String lobbyName = (String) headerAccessor.getSessionAttributes().get("lobbyName");
if(lobbyName != null) {
SocketMessage message = new SocketMessage();
messagingTemplate.convertAndSend("/topic/public/"+lobbyName, message);
}
}
In my application,i have activeMq to send the message from client to server and vice versa.I run it as a standalone server.So when a client machine sends the message,the messages are passed in the activeMq queue and then retrieve by the server(my Application) if and only if the transaction is done locally,meaning the client machine and server(my application) live in the same computer. But when i run the client and server from two different computer meaning server in one and client in another then the client can only establish connection to the server but the messages are not passed to the activeMq queue.I think this is something with activeMq problem.
can anyone tell me how to solve this?
thanks
here is the code which passes the data sent by client to the queue.
package event.activeMq;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;
import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.console.command.store.amq.CommandLineSupport;
import org.apache.activemq.util.IndentPrinter;
public class ProducerTool extends Thread {
private Destination destination;
private int messageCount = 1;
private long sleepTime;
private boolean verbose = true;
private int messageSize = 1000;
private static int parallelThreads = 1;
private long timeToLive;
private String user = ActiveMQConnection.DEFAULT_USER;
private String password = ActiveMQConnection.DEFAULT_PASSWORD;
private String url = ActiveMQConnection.DEFAULT_BROKER_URL;
private String subject = "CLOUDD.DEFAULT";
private boolean topic;
private boolean transacted;
private boolean persistent;
private static Object lockResults = new Object();
private static String DateTime="";
private static String TaskID="";
private static String UniqueEventID="";
private static String Generator="";
private static String GeneratorBuildVsn="";
private static String Severity="";
private static String EventText="";
private static String SubsystemID="";
private static String EventNumber="";
private static String atmId="";
public void element(String[] element) {
this.DateTime = element[0];
this.TaskID = element[1];
this.Generator = element[2];
this.Severity = element[3];
this.EventText = element[4];
this.SubsystemID = element[5];
this.EventNumber = element[6];
this.GeneratorBuildVsn = element[7];
this.UniqueEventID = element[8];
this.atmId = element[9];
}
public static void main(String[] args) {
System.out.println("came here");
ArrayList<ProducerTool> threads = new ArrayList();
ProducerTool producerTool = new ProducerTool();
producerTool.element(args);
producerTool.showParameters();
for (int threadCount = 1; threadCount <= parallelThreads; threadCount++) {
producerTool = new ProducerTool();
CommandLineSupport.setOptions(producerTool, args);
producerTool.start();
threads.add(producerTool);
}
while (true) {
Iterator<ProducerTool> itr = threads.iterator();
int running = 0;
while (itr.hasNext()) {
ProducerTool thread = itr.next();
if (thread.isAlive()) {
running++;
}
}
if (running <= 0) {
System.out.println("All threads completed their work");
break;
}
try {
Thread.sleep(1000);
} catch (Exception e) {
}
}
}
public void showParameters() {
System.out.println("Connecting to URL: " + url);
System.out.println("Publishing a Message with size " + messageSize + " to " + (topic ? "topic" : "queue") + ": " + subject);
System.out.println("Using " + (persistent ? "persistent" : "non-persistent") + " messages");
System.out.println("Sleeping between publish " + sleepTime + " ms");
System.out.println("Running " + parallelThreads + " parallel threads");
if (timeToLive != 0) {
// System.out.println("Messages time to live " + timeToLive + " ms");
}
}
public void run() {
Connection connection = null;
try {
// Create the connection.
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(user, password, url);
connection = connectionFactory.createConnection();
connection.start();
// Create the session
Session session = connection.createSession(transacted, Session.AUTO_ACKNOWLEDGE);
if (topic) {
destination = session.createTopic(subject);
} else {
destination = session.createQueue(subject);
}
// Create the producer.
MessageProducer producer = session.createProducer(destination);
if (persistent) {
producer.setDeliveryMode(DeliveryMode.PERSISTENT);
} else {
producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
}
if (timeToLive != 0) {
producer.setTimeToLive(timeToLive);
}
// Start sending messages
sendLoop(session, producer);
// System.out.println("[" + this.getName() + "] Done.");
synchronized (lockResults) {
ActiveMQConnection c = (ActiveMQConnection) connection;
// System.out.println("[" + this.getName() + "] Results:\n");
c.getConnectionStats().dump(new IndentPrinter());
}
} catch (Exception e) {
// System.out.println("[" + this.getName() + "] Caught: " + e);
e.printStackTrace();
} finally {
try {
connection.close();
} catch (Throwable ignore) {
}
}
}
protected void sendLoop(Session session, MessageProducer producer) throws Exception {
for (int i = 0; i < messageCount || messageCount == 0; i++) {
TextMessage message = session.createTextMessage(createMessageText(i));
if (verbose) {
String msg = message.getText();
if (msg.length() > 50) {
msg = msg.substring(0, 50) + "...";
}
// System.out.println("[" + this.getName() + "] Sending message: '" + msg + "'");
}
producer.send(message);
if (transacted) {
// System.out.println("[" + this.getName() + "] Committing " + messageCount + " messages");
session.commit();
}
Thread.sleep(sleepTime);
}
}
private String createMessageText(int index) {
StringBuffer buffer = new StringBuffer(messageSize);
buffer.append("DateTime "+DateTime+" EventNumber "+EventNumber+" TaskID "+TaskID+" AtmId "+atmId+
" Generator "+Generator+" GeneratorBuildVsn "+GeneratorBuildVsn+" Severity "+Severity+
" UniqueEventID "+UniqueEventID+" EventText "+EventText+" SubsystemID "+SubsystemID+" End ");
if (buffer.length() > messageSize) {
return buffer.substring(0, messageSize);
}
for (int i = buffer.length(); i < messageSize; i++) {
buffer.append(' ');
}
DateTime="";
EventNumber="";
TaskID="";
atmId="";
Generator="";
GeneratorBuildVsn="";
Severity="";
UniqueEventID="";
EventText="";
SubsystemID="";
return buffer.toString();
}
public void setPersistent(boolean durable) {
this.persistent = durable;
}
public void setMessageCount(int messageCount) {
this.messageCount = messageCount;
}
public void setMessageSize(int messageSize) {
this.messageSize = messageSize;
}
public void setPassword(String pwd) {
this.password = pwd;
}
public void setSleepTime(long sleepTime) {
this.sleepTime = sleepTime;
}
public void setSubject(String subject) {
this.subject = subject;
}
public void setTimeToLive(long timeToLive) {
this.timeToLive = timeToLive;
}
public void setParallelThreads(int parallelThreads) {
if (parallelThreads < 1) {
parallelThreads = 1;
}
this.parallelThreads = parallelThreads;
}
public void setTopic(boolean topic) {
this.topic = topic;
}
public void setQueue(boolean queue) {
this.topic = !queue;
}
public void setTransacted(boolean transacted) {
this.transacted = transacted;
}
public void setUrl(String url) {
this.url = url;
}
public void setUser(String user) {
this.user = user;
}
public void setVerbose(boolean verbose) {
this.verbose = verbose;
}
}
you need to update your questin with answers on this questions:
What os do you use?
Do you have a firewall like software on pc?
Could you provide here ActiveMQ conf file?
Could you provide a function
which implemented connection establishment?
upd:
I do't understand all your logic but i thk bug here:
try {
Thread.sleep(1000);
} catch (Exception e){
e.printStackTrace();
}
And never never never catch all exceptions! it's very dangerous.
if you want to catch exception, you need to handle it.