I am trying to make the concurrent session to MQTT server and all clients will disconnect once all the connections are made.
In the below publisher code I am trying to make concurrents sessions each sending 50 messages. And like this 500 threads will create and each will send 50 messages. But for creating 100 connections it is taking 10 minutes. Is there any mistake in coding and is it possible to decrease the rate of connection speed changing in below code, because the same thing I have written in Golang the rate of connection is high there.
Below is the publisher code:
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttPersistenceException;
import org.eclipse.paho.client.mqttv3.MqttSecurityException;
import org.eclipse.paho.client.mqttv3.MqttTopic;
public class Publisher extends Thread{
public static final String test_topic = "test";
private MqttClient client;
public static final String BROKER_URL = "tcp://192.168.1.129:1883";
CountDownLatch latch;
public Publisher(CountDownLatch latch) {
super();
this.latch = latch;
}
public void Publisher() {
String clientid=Thread.currentThread().getName();
System.out.println("=========== "+clientid);
MqttConnectOptions options = null;
try {
client = new MqttClient(BROKER_URL, clientid);
options = new MqttConnectOptions();
options.setCleanSession(true);
options.setMaxInflight(50);
client.connect(options);
} catch (MqttException e) {
try {
client.connect(options);
} catch (MqttSecurityException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (MqttException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
e.printStackTrace();
//System.exit(1);
}
}
#Override
public void run() {
// TODO Auto-generated method stub
Publisher();
System.out.println(Thread.currentThread().getName());
try {
for(int i=0;i<50;i++)
{
//Thread.sleep(20);
publishTemperature();
}
} catch (MqttPersistenceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MqttException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} /*catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
}
public void publishTemperature() throws MqttPersistenceException, MqttException {
final MqttTopic test = client.getTopic(test_topic);
final String temperature=""{\"test\":\"test\"}"";
test.publish(new MqttMessage(temperature.getBytes()));
//System.out.println("Published data. Topic: " + "test" + " Message: " + temperature);
}
public MqttClient getClient() {
return client;
}
public void setClient(MqttClient client) {
this.client = client;
}
}
Below is the main method:
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttPersistenceException;
public class test {
static Publisher[] Publisher=null;
public static void main(String[] args) throws MqttPersistenceException, MqttException, InterruptedException {
final CountDownLatch latch = new CountDownLatch(50);
Publisher = new Publisher[500];
for(int i=0;i<500;i++)
{
Thread.sleep(10);
Publisher[i]=new Publisher(latch);
Publisher[i].start();
}
latch.await();
for(int i=0;i<500;i++)
{
//Thread.sleep(10);
Publisher[i].getClient().disconnectForcibly(25);
}
}
}
Here all connections will connect and make persistent connection up to reaching 500 connections. After that, all connections will disconnect once.
Remove the following line:
Publisher[i].join();
The docs for Thread.join() say the following:
public final void join()
throws InterruptedException
Waits for this thread to die.
An invocation of this method behaves in exactly the same way as the
invocation
join(0)
This means that every time round the loop it will stop and wait for that thread to complete it's task before creating the new one.
If you remove that call it will allow all the threads to run in parallel.
Related
Since I am stuck for this for a week now and still haven't firgured it out I try to express what I want as cleary as possible.
I have a Server which can handle Multiple Clients and communicates with them.
Whenever a client connects, the server passes the Client's request to my class RequestHandler, in which the clients commands are being processed.
If one of the clients says "SHUTDOWN", the server is supposed to cut them loose and shut down.
It doesn't work.
If only one client connects to the server, the server seems to be stuck in the accept() call and I do not know how to fix this.
THERE is already one response, but please do not take note of it, it was on a different topic which is outdated
I have two approaches and both don't seem to work.
1)If the client writes "SHUTDOWN", the shutdownFlag is set to true (in hope to exit the while loop)
2)If the client writes "SHUTDOWN", the static method shutdown() is called on the Server, which should shut him down
Below you see the implementation of my Server class, the other two classes involved are Client(all he does is connect to the Socket) and RequestHandler (this class processes the Input and writes it) .
I am 98% sure the problem lies within the Server class.
Below this is an even shorter version of the Server with just the methods without any Console outputs which might help understanding it in case you want to copy the code
public class Server {
public static final int PORTNUMBER = 8540;
public static final int MAX_CLIENTS = 3;
public static boolean shutdownFlag = false;
public static ExecutorService executor = null;
public static ServerSocket serverSocket = null;
public static void main(String[] args) {
ExecutorService executor = null;
try (ServerSocket serverSocket = new ServerSocket(PORTNUMBER);) {
executor = Executors.newFixedThreadPool(MAX_CLIENTS);
System.out.println("Waiting for clients");
while (!shutdownFlag) {
System.out.println("shutdown flag ist : " + shutdownFlag);
Socket clientSocket = serverSocket.accept();
Runnable worker = new RequestHandler(clientSocket);
executor.execute(worker);
System.out.println("Hallo");
}
if (shutdownFlag) {
System.out.println("Flag is on");
try {
executor.awaitTermination(10, TimeUnit.SECONDS);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
//Stop accepting requests.
serverSocket.close();
} catch (IOException e) {
System.out.println("Error in server shutdown");
e.printStackTrace();
}
serverSocket.close();
}
System.out.println("shutting down");
} catch (IOException e) {
System.out
.println("Exception caught when trying to listen on port "
+ PORTNUMBER + " or listening for a connection");
System.out.println(e.getMessage());
} finally {
if (executor != null) {
executor.shutdown();
}
}
}
public static void shutdown(){
if (shutdownFlag) {
System.out.println("Flag is on");
try {
executor.awaitTermination(10, TimeUnit.SECONDS);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
//Stop accepting requests.
serverSocket.close();
} catch (IOException e) {
System.out.println("Error in server shutdown");
e.printStackTrace();
}
try {
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class Server {
public static final int PORTNUMBER = 8540;
public static final int MAX_CLIENTS = 3;
public static boolean shutdownFlag = false;
public static ExecutorService executor = null;
public static ServerSocket serverSocket = null;
public static void main(String[] args) {
ExecutorService executor = null;
try (ServerSocket serverSocket = new ServerSocket(PORTNUMBER);) {
executor = Executors.newFixedThreadPool(MAX_CLIENTS);
while (!shutdownFlag) {
Socket clientSocket = serverSocket.accept();
Runnable worker = new RequestHandler(clientSocket);
executor.execute(worker);
}
if (shutdownFlag) {
try {
executor.awaitTermination(10, TimeUnit.SECONDS);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
serverSocket.close();
}
} catch (IOException e) {
} finally {
if (executor != null) {
executor.shutdown();
}
}
}
public static void shutdown() {
if (shutdownFlag) {
try {
executor.awaitTermination(10, TimeUnit.SECONDS);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
If you move the code in main into an instance method on Server (we'll say run here) you can just do new Server().run() inside main. That way you have an instance (this) to work with inside your run method.
Something like this:
class Server {
private boolean shutdownFlag = false; // This can't be static anymore.
public static final Server SERVER = new Server();
public static void main(String[] args) {
SERVER.run();
}
private void run() {
// Here goes everything that used to be inside main...
// Now you have the Server.SERVER instance to use outside the class
// to shut things down or whatever ...
}
}
This pattern isn't actually that great but better would be too long for here. Hopefully this gets you off to a good start.
I am new in OSGI and i have current aim. I have 10 threads, it's writing their names in a file. After recording thread sleep random 0..1 sec. This all must be a bundle. I create it, but i'm not sure Is this correct. Can any comments?
package helloworld;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import writer.StartThreads;
public class Activator implements BundleActivator {
public void start(BundleContext context) throws Exception {
System.out.println("Start Thred!!");
new StartThreads().Execute();
}
public void stop(BundleContext context) throws Exception {
System.out.println("Goodbye World!!");
}
}
1
package writer;
import writer.WriterLogs;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class StartThreads {
public static void Execute() {
BufferedWriter writer = null;
File textFile = new File("threadLog.txt");
// if file doesnt exists, then create it
if (!textFile.exists()) {
try {
textFile.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
writer = new BufferedWriter(new FileWriter(textFile, true));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i = 0; i < 10; i++) {
WriterLogs wrt = new WriterLogs(writer);
Thread worker = new Thread(wrt);
worker.setName("Nisha-" + i);
worker.start();
try {
worker.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
2
package writer;
import java.io.BufferedWriter;
import java.io.IOException;
public class WriterLogs implements Runnable {
private BufferedWriter writer;
public WriterLogs(BufferedWriter wr) {
this.writer = wr;
}
#Override
public void run() {
try
{
try {
synchronized(this.writer) {
this.writer.write(Thread.currentThread().getName() + "\n");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// set random 0...1 s.
Thread.sleep((long)(Math.random() * 1000));
System.out.println(Thread.currentThread().getName());
}
catch (InterruptedException interruptedException)
{
/*Interrupted exception will be thrown when a sleeping or waiting
* thread is interrupted.
*/
System.out.println( Thread.currentThread().getName() +interruptedException);
}
}
}
This is not correct. Like Boris the Spider states, when your bundle stops, you should free any resources and stop any processing the bundle was doing. So from the stop method you should somehow signal your threads to stop as soon as they can.
In practice you might get away with letting the code run, but this is definitely not how you should write your code in OSGi (which is what you're asking).
I am newbie in java networking ,I am trying to make a server application in java called instant messaging without GUI. So whenever i run the program it says
" Main method not found in class Methods, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application" -ECLIPSE
Please help me what's wrong in my code.
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
// FIRST FILE //
public class main{
public static void main (String[] args) {
Server s=new Server();
s.runningserver();
}
}
//SECOND FILE//
public class Server {
private ObjectOutputStream output;
private ObjectInputStream input;
private ServerSocket server;
private Socket connection;
//wait For Connection,then display connection information
private void waitforConnection() {
System.out.println("wait for Someone to Connect.....\n");
try {
connection=server.accept();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("error In Acceptance of Server!!\n...");
}
System.out.println(("Connection Established"+connection.getInetAddress().getHostName()));
}
//Setting Up Streams to Get Input and Output
private void setupStreams(){
try {
output=new ObjectOutputStream(connection.getOutputStream());
output.flush();
input=new ObjectInputStream(connection.getInputStream());
System.out.println("Your Streams are Perfectly Working...");
} catch (IOException e) {
// TODO Auto-generated catch block
System.err.println("Error Found! in Streaming Connectionos");
e.printStackTrace();
}
}
// While Chatting Method....!!//
private void whileChatting() throws IOException{
String Message="You are now Connected!!\n";
sendMessage(Message);
//abletoType(true);
do{
try{
Message=(String) input.readObject();
System.out.println("\n"+Message);
}
catch(ClassNotFoundException e ){
System.out.println("wtf---Fuck\n YOu\n Bloody\n HAcker!!!\n");
}
}
while(!Message.equals("CLIENT--END"));
}
// Closing All Streams and Socket after you are done//
private void closeCrap(){
System.out.println("\nClosing Connection...........Bye Bye\n");
//abletoType(false);
try {
output.close();
input.close();
connection.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("Couldn't Close Connections!");
}
}
//Sending Messages to Client
private void sendMessage(String message){
try {
output.writeObject("SERVER--- "+message);
output.flush();
System.out.println("\nServer- "+message);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("Dude I cant Send yeaah..");
}
}
// Setting up the Server
public void runningserver(){
try {
server=new ServerSocket(4444,100);
while(true){try{
//connect and Have connection
waitforConnection();
setupStreams();
whileChatting();
}
finally{
closeCrap();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
EDIT: Here is the solution and I checked it and for me it works (run the MainClass.java file!):
//MainClass.java file:
public class MainClass {
public static void main (String[] args) {
Server s=new Server();
s.runningserver();
}
}
//Server.java file:
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
private ObjectOutputStream output;
private ObjectInputStream input;
private ServerSocket server;
private Socket connection;
// wait For Connection,then display connection information
private void waitforConnection() {
System.out.println("wait for Someone to Connect.....\n");
try {
connection = server.accept();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("error In Acceptance of Server!!\n...");
}
System.out.println(("Connection Established" + connection
.getInetAddress().getHostName()));
}
// Setting Up Streams to Get Input and Output
private void setupStreams() {
try {
output = new ObjectOutputStream(connection.getOutputStream());
output.flush();
input = new ObjectInputStream(connection.getInputStream());
System.out.println("Your Streams are Perfectly Working...");
} catch (IOException e) {
// TODO Auto-generated catch block
System.err.println("Error Found! in Streaming Connectionos");
e.printStackTrace();
}
}
// While Chatting Method....!!//
private void whileChatting() throws IOException {
String Message = "You are now Connected!!\n";
sendMessage(Message);
// abletoType(true);
do {
try {
Message = (String) input.readObject();
System.out.println("\n" + Message);
} catch (ClassNotFoundException e) {
System.out.println("wtf---Fuck\n YOu\n Bloody\n HAcker!!!\n");
}
} while (!Message.equals("CLIENT--END"));
}
// Closing All Streams and Socket after you are done//
private void closeCrap() {
System.out.println("\nClosing Connection...........Bye Bye\n");
// abletoType(false);
try {
output.close();
input.close();
connection.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("Couldn't Close Connections!");
}
}
// Sending Messages to Client
private void sendMessage(String message) {
try {
output.writeObject("SERVER--- " + message);
output.flush();
System.out.println("\nServer- " + message);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("Dude I cant Send yeaah..");
}
}
// Setting up the Server
public void runningserver() {
try {
server = new ServerSocket(4444, 100);
while (true) {
try {
// connect and Have connection
waitforConnection();
setupStreams();
whileChatting();
} finally {
closeCrap();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I can run that without an exception.
The Problem is your main method
public static void main (String[] args) {}
Is not in the class where you run it.
//separate file A.java
public class A
{}
//separate file B.java
public class B
{
public static void main (String[] args) {}
}
If you now run B, it works, because B.java has a main method. BUT: if you run A.java it says:
no main methode found. The file you want to run (A, B, etc. must have a main method defined)
If you run a java file, it will look for a main method (start point of execution).
The main method must be a method of the class:
import java.net.Socket;
public class Server {
public static void main (String[] args) {
Server s=new Server();
s.runningserver();
}
So it must come after the class declaration.
Hi I am trying out java multicast.
I have a WIFI router at - 10.0.0.1 (gateway)
and two nodes:
Node_1 - 10.0.0.4
Node_2 - 10.0.0.3
My IP Multicast sender looks like:
private static class Sender extends Thread
{
// Create the socket but we don't bind it as we are only going to send data
private MulticastSocket s;
private static int senderPort = 15000;
private static String group = "225.4.5.6";
public Sender() throws IOException
{
s = new MulticastSocket(senderPort);
s.setInterface(InetAddress.getLocalHost());
s.joinGroup(InetAddress.getByName(group));
}
#Override
public void run() {
Integer data = 1;
while(true)
{
try {
s.send(new DatagramPacket(data.toString().getBytes(), data.toString().getBytes().length, InetAddress.getByName(group), senderPort));
Thread.sleep(3000);
data++;
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
System.out.println("Sender - UnknownHostException");
}catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("Sender - IOException");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
And my IP Multicast receiver looks like:
private static class Receiver extends Thread
{
private MulticastSocket s;
private static int receiverPort = 15000;
private static String group = "225.4.5.6";
public Receiver() throws IOException
{
s = new MulticastSocket(receiverPort);
s.setInterface(InetAddress.getLocalHost());
s.joinGroup(InetAddress.getByName(group));
}
#Override
public void run() {
while (true)
{
byte buf[] = new byte[1024];
DatagramPacket pack = new DatagramPacket(buf, buf.length);
try {
System.out.println("Receiver waiting for data");
s.receive(pack);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.write(pack.getData(),0,pack.getLength());
System.out.println();
}
}
}
When I have both the Sender and Receiver in the same Node it WORKS but when I have them in different Nodes it does NOT WORK.
What is it that I am missing here??
By calling setInterface() to the local host you are preventing the joinGroup() message from leaving the current host. That doesn't matter in the sender, because a sender doesn't have to join the group anyway, but in the receiver it will prevent other hosts, routers, etc. from knowing that the receiving host is in the group.
Just remove it.
I have code which needs to do something like this
There is a list of classes each with some method (lets say execute()). I need to invoke that method on each class and there is a fixed timeOut for each invocation. Now, one of the class's execute method is badly written and results in a timeout due to which the jvm does not exit. I am running the class like this.
java ExecutorServiceTest execute TestClass1 TestClass2 TestClass3
Why does the jvm not exit after completing the execution of the code?
I get the following output
In class 1
In Class 2
java.util.concurrent.TimeoutException
at java.util.concurrent.FutureTask$Sync.innerGet(Unknown Source)
at java.util.concurrent.FutureTask.get(Unknown Source)
at ExecutorServiceTest.main(ExecutorServiceTest.java:78)
java.util.concurrent.TimeoutException
at java.util.concurrent.FutureTask$Sync.innerGet(Unknown Source)
at java.util.concurrent.FutureTask.get(Unknown Source)
The second class's execute times out and after that, the third class's execute also times out. Why does the third class's execute time out?
The jvm does not exit after the execution is complete. What is the reason? Also why is the TestClass3 execute timedout?
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
class Task implements Callable<String> {
Object instance;
Method m;
Object[] input;
Task(Object instance, Method m, Object[] input) {
this.instance = instance;
this.m = m;
this.input = input;
}
public String call() {
String s = "initial";
try {
m.invoke(instance, input);
}
catch (RuntimeException e) {
}
catch (Exception e) {
}
finally {
}
return s;
}
}
public class ExecutorServiceTest {
public static void main(String[] args) {
String methodName = args[0];
String className;
List<Object> instanceList = new ArrayList<Object>();
for (int i=1;i<args.length;i++) {
className = args[i];
Object o = null;
try {
o = Class.forName(className).newInstance();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
instanceList.add(o);
}
ExecutorService executor = Executors.newSingleThreadExecutor();
Iterator<Object> iter = instanceList.iterator();
while (iter.hasNext()) {
Object o = iter.next();
Method m = null;
try {
m = o.getClass().getDeclaredMethod(methodName, new Class[] {});
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Task t = new Task(o,m,new Object[]{});
Future<String> fut = executor.submit(t);
try {
fut.get(2,TimeUnit.SECONDS);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TimeoutException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
executor.shutdown();
}
}
public class TestClass1 {
public void execute() {
System.out.println("In class 1");
}
}
public class TestClass2 {
public void execute() {
System.out.println("In class 2");
boolean b = true;
while (b) {
}
}
}
public class TestClass3 {
public void execute() {
System.out.println("In class 3");
}
}
ExecutorService.shutdown() doesn't actually stop any running executors/threads, it just tells the service to stop accepting new tasks:
void shutdown()
Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted. Invocation has no additional effect if already shut down.
Your TestClass2 instance is never going to stop running because it has a while(true) loop which is never halted.
If you want to stop the ExecutorService immediately, you can use awaitTermination(long timeout, TimeUnit unit) or shutdownNow().
You need to call executor.shutdown() or create a daemon thread (using appropriate ThreadFactory passed to Executors.newSingleThreadExecutor()