In one package I have two different classes Client.java and Server.java
I want to make this package jar, i mean executable.
First I want the Server class to run and after 2-3 seconds I want Client method to run. Is it possible?
Thank you
You have to leave only one main method and run your server and client in separate threads from it.
To do it, take a look at Runnable interface. Your server class and client class should implement it. Then you have to move the logic, used to start server and client to it's run() method.
class Server implements Runnable {
#Override
public void run() {
//your server starting logic here
}
}
class Client implements Runnable {
#Override
public void run() {
//your client starting logic here
}
}
After that, you can modify your main method, to start server and client, like:
public static void main(String args[]) throws InterruptedException {
Server server = new Server();
Client client = new Client();
Thread tServer = new Thread(server);
tServer.start();
//here you can wait some time to Server started
Thread tClient = new Thread(client);
tClient.start();
}
Related
I need to run a Server and Client in a application that trade string messages with each other(a chat), the code for this is working, part of it was provided by the teacher, but i'm stuck in one thing.
I want to run a class named "App", who creates a new Server and a new Client, but when i run both of then in the class, only one works.
package app;
import udp.Client;
import udp.Server;
public class App {
public static void main(String[] args) {
Server s = new Server();
s.Start();
Client c = new Client();
c.Start();
}
}
So to run the both of then, Server and Client, i need to comment out the client one, run the Server instance, then comment out the Server one, and run the Client instance, both classes initialize a thread.
How can i run both of then without that improvisation? I wanna hit "Run", and the code pops up the Server and the Client window.
I can provide the rest of the code if it's necessary.
new Thread(() ->
{
Server s = new Server();
s.Start();
}).start();
new Thread(() ->
{
Client c = new Client();
c.Start();
}).start();
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I have a problem when I want to run several methods not in the main thread. I created a class extends from Runnable and put all my tasks there. There are a lot of tasks actually. Then in the main thread I created a new instance of Thread and passed my runnable class as a parameter, but what I got is that the run method is the only code which executed in the thread, and if call any method inside the runnable class it will execute in the main thread instead of the new thread.
Example:
public class ConnectionManager implements Runnable {
#Override
public void run() {
login();
}
public void login() {
//Login Logic
}
public void sendMessage() {
//Send Message Via TCP Connection
}
public void updateInfo() {
//Update Information
}
public void logOut() {
//LogOut Logic
}
}
Now I wanted to call any of these methods in another thread, so I did this:
public class Login implements SomeInterface {
private Thread thread;
private ConnectionManager connection;
public void main(String[] args) {
connection = new ConnectionManager();
thread= new Thread(connection);
thread.start(); // This will execute the run method and the login process works fine.
}
#Override
public void someCallback() {
connection.sendMessage();//this call is not executed and block the main thread !!
}
}
What am I supposed to do to run all my methods in another thread without making a new thread for each method?
You should split your logic
public class Logger implements Runnable {
#Override
public void run() {
// login logic here;
}
}
public class MessegeSender implements Runnable {
#Override
public void run() {
//Send Message Via TCP Connection
}
}
public class MessegeSender implements Runnable {
#Override
public void run() {
//Update Information
}
}
public class MessegeSender implements Runnable {
#Override
public void run() {
//LogOut Logic
}
}
And then in some client:
Runnable logger = new Logger(credentials);
Executors.newSingleThreadExecutor().execute(logger);
Well this is how threads work in java. One possibility is to use Actors in java. You will have to download the Akka framework here:http://akka.io/downloads/.
Actors works by messages, they act in a separate process and are even driven messages. In other words depending on the message you send to the actor it will process a corresponding method.
Check in the following link for instances: http://doc.akka.io/docs/akka/snapshot/java/untyped-actors.html
The method run equivalent in java actors is onReceive().
And to send a message to the actor, myActor.tell(...)
Hope this helps you!!!!
Well, that is the way threads work in Java. When You call connection.sendMessage() Your method just treats ConnectionManager and runs it's code. You need to execute Your method in another threads run(), or it will not run. Perhaps You need a way to comunicate with Your thread to make it execute a method in run() or just explore the possibilities that Future objects give You?
That's how does Runnable or Multithread handling work.
You should never call the run() directly and only this function and other function calls inside this function are executed in the new thread.
Basically your Runnable class should only contains one public function: the run() and you should not call it directly...
I suggest you to put other functions in their own classes. As you can see the workflow is not continuous, sendMessage() is not called directly after login() (otherwise you can do it inside run() and don't need that someCallback()).
Otherwise what should that new thread supposed to do in the time between? block and wait for sendMessage()? That's not a good design. So you should start a new thread for sendMessage().
My server aperiodically receives join requests from new clients. Upon receiving a new join request, the server runs a service that can be finished real quick. I implement the service as a Java class (called JC) implementing the Runnable interface. I have parameters within the JC class.
At the caller side, I like to have only one instance (or static) of the JC. My question is how to trigger the run() method in the JC every time. Please show me some code. Thanks.
Hope following edits make sense, which is my current implementation.
In the Server that wants to trigger thread executing:
public class Server {
private static RealService mm = new RealService();
private static void update(){
new Thread(mm).start();
}
}
In the Service class:
public class RealService implements Runnable{
#Override
public void run() {
// TODO Auto-generated method stub
// Do something
}
}
You're question is not really clear here, but I would suggest reading about TimerTask in Java
You could use a socket to listen for incoming requests, the server can spawn a new thread each time there is a request. Once the thread completes, you should intimate the client.
You could read about how a concurrent server works.
I have the following server class that export himself for JRMP and IIOP:
public class FooServer implements RemoteInt{
FooServer(){
UnicastRemoteObject.exportObject(this);
PortableRemoteObject.exportObject(this);
}
public boolean remoteMethod() throws RemoteException{
// some stuff
return false;
}
}
and the following setup class which creates the server and register it to a running register:
public class Setup{
public static void main(String[] args){
RemoteInt serv = new FooServer();
Naming.rebind("//localhost/server", this);
}
}
The problem is that when Setup finishes its job, it waits for the FooServer to terminate. Instead I would like to exit from Setup class, leaving the FooServer running.
How can I do?
You can't. The remote object is exported from the current JVM and it keeps it running until you unexport it. Note that the main() method does exit, but the RMI/JRMP and RMi/IIOP listening threads are still running so the JVM doesn't exit.
using the Controller.java, I' implementing the run() in NetworkDiscovery.java which queries all the machine in the subnet . The active machines reply with their status. This happens at regular intervals.
public class Controller {
NetworkDiscovery n;
public static int discoveryInterval=2000;
PM pmList;
List pmlist=(List) new PM();
public static void main(String[] args) throws UnknownHostException{
Timer t1=new Timer();
t1.scheduleAtFixedRate(new NetworkDiscovery(), 2000, discoveryInterval);
}
public class NetworkDiscovery extends TimerTask{
InetAddress controllerIP;
int controllerPort;
NetworkDiscovery() throws UnknownHostException {
controllerIP=InetAddress.getLocalHost();
controllerPort=4455;
}
#Override
public void run() {
try {
byte[] recvBuf = new byte[5000];
DatagramPacket packet = new DatagramPacket(recvBuf, recvBuf.length);
DatagramSocket dSock = new DatagramSocket(4445);
dSock.receive(packet);
//implementation related code follows
**dSock.close();**
}
}
On the client's side a similar Datagram socket is opened and objects are received/sent.
The problem is that on the COntroller's side, I'm executing NetworkDiscovery's run() after a specific time interval and during the second execution it says -
java.net.BindException: Address already in use
Since I'm closing the Controller's socket by close(), why does it still show that this address is already being in use? How can I make sure that during the next iteration, the controller starts over fresh call of networkDiscovery?
Perhaps the second task starts before the first was completly executed? Have you tried to insert debug messages and see if the first task was finished?