Windows Console redirecting - java

I'm trying to write a program, which starts an process for the windows console (cmd) and redirects the Input,Output and Errorstreams to System.in/out/err. Also, if the process is closed (via the command exit) my program should shutdown.
I've written a solution, that works kind of. The only problem is my used thread don't notice the process is shutted down. Also I don't know if it is nessecery to write a new Thread for all this streams, so if you know an easier solution to redirect the streams I'd like to hear about it.
Here my SSCCE:
public class Main {
public static boolean run = true;
public static void main(String[] args) throws IOException {
ProcessBuilder p = new ProcessBuilder("cmd");
final Process pr = p.start();
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
pr.waitFor();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("test");
run = false;
}
});
// read(is);
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
while (run)
try {
write(System.in, pr.getOutputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
while (run)
try {
write(pr.getInputStream(), System.out);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("finish");
}
}).start();
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
while (run)
try {
write(pr.getErrorStream(), System.err);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
public static void write(InputStream is, OutputStream os)
throws IOException {
byte[] buf = new byte[1024];
int len = is.read(buf);
if (len != -1) {
byte[] data = new byte[len];
for (int i = 0; i < len; i++) {
data[i] = buf[i];
}
os.write(data);
os.flush();
}
}
}
What happens, is that I create a new Thread for every redirection of the streams, and the redirection itself happens via the write(inputStream,outputStream) method.
But the thread I use to check if the process is closed (pr.waitFor()) doesn't work as i thought it would. So I don't get noticed if the cmd is closed.
EDIT2
Ok I just forgot to start the Thread. But now I was able to get close to the problem.
The redirection of System.in to the process.getOutputStream() doesn't notice that the process is going to be closed. That's because is.read(buf) is a blocking method. So if I try to write a new command to the Process, then it notices that the streams should be closed and finishes the program.
If there is any solution for redirecting the Streams without threads, I'd like to implement it that way. I think this would be easier to use.

the main problem is you didn't do .start on the thread but i also want to suggest an improvement
wait for the process in the main thread:
public class Main {
public static boolean run = true;
public static void main(String[] args) throws IOException {
ProcessBuilder p = new ProcessBuilder("cmd");
final Process pr = p.start();
// read(is);
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
while (run)
try {
write(System.in, pr.getOutputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
while (run)
try {
write(pr.getInputStream(), System.out);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("finish");
}
}).start();
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
while (run)
try {
write(pr.getErrorStream(), System.err);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
try {
pr.waitFor();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("test");
run = false;
}
public static void write(InputStream is, OutputStream os)
throws IOException {
byte[] buf = new byte[1024];
int len = is.read(buf);
if (len != -1) {
byte[] data = new byte[len];
for (int i = 0; i < len; i++) {
data[i] = buf[i];
}
os.write(data);
os.flush();
}
}
}

I'm guessing that is because your main thread could exit before all those threads complete. Try adding pr.waitFor() right at the end of your main function.

Related

Best way to write the multithread

I have to make an assignment with multi-threading. I have 2 classes for movement of a crane.
In this cases class there are 2 options, whether the claws ultrasonic sensor sees a box or not (seen down below).
In the other class i have to pick up a box from the initial starting position and put it to another position from 1-3(which is a distance based on keypress).
How do i write the class I am missing?
public class Cases extends Thread
UltrasonicSensor usc= new UltrasonicSensor(SensorPort.S1);
int box=0;
boolean isBoxThere=true;
public Cases cases;
public void error() throws InterruptedException
{
LCD.drawString("There are no boxes", 0, 0);
LCD.drawString(" At the location", 0, 1);
Button.waitForAnyPress();
LCD.clear();
Thread.sleep(1000);
}
//Claw movement
public void down() throws InterruptedException{
MotorPort motorY=MotorPort.B;
motorY.resetTachoCount();
motorY.controlMotor(85, 1);
stopY();
}
public void up() throws InterruptedException{
MotorPort motorY = MotorPort.B;
motorY.controlMotor(85, 2);
while(motorY.getTachoCount()>0); //After the crane grabs the box it lifts it back up
stopY();
}
public void clawclose() throws InterruptedException{
MotorPort motorC=MotorPort.C;
motorC.controlMotor(65, 2);
{
Thread.sleep(505); //Thread sleep is used for the cranes precise stopping
}
motorC.controlMotor(100, 3);
{
Thread.sleep(1000);
}
stopC();
}
public void clawopen() throws InterruptedException{
MotorPort motorC=MotorPort.C;
{
Thread.sleep(520);
}
motorC.controlMotor(100, 3);
{
Thread.sleep(1000);
}
stopC();
}
//Codes for stopping of Motors
public static void stopY () throws InterruptedException{
MotorPort motorY = MotorPort.B;
motorY.controlMotor(100, 3);
Thread.sleep(1000);
}
public static void stopC () throws InterruptedException{
MotorPort motorC = MotorPort.C;
motorC.controlMotor(100, 3);
Thread.sleep(1000);
}
public void run()
{
try
{
while(true)
{
switch(box)
{
case 1:
{
while(box==1)
{
isBoxThere=true;
try {
clawopen();
} catch (InterruptedException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
down();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
while(usc.getDistance()<10)
{
try
{
Thread.sleep(100);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
try
{
clawclose();
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
case 2:
{
while(box==0)
{
isBoxThere=false;
try
{
error();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}
}
}
finally{}
}
}

Closing clients on a multithreaded chat server

i am currently working on a chat server as a project an need a bit of help. i have a multithreaded chat server where i want the clients to be able to close their chat window without crashing the server because it loses connection. So far so good. i have a working gui, and when i have a single client logged in to the server it works just fine to close the window and so closing the clientIOProcessor without the server crashing.
However, when i have multiple clients logged in to the server and want to close one of them the hole thing crashes
here is the ClientIOProcessor:
public class ClientIOProcessor extends Object implements Runnable, InputListener {
private ObjectInput socketInput;
private ObjectOutput socketOutput;
private boolean keepRunning;
private ClientModelDistributor assignedModelDistributor;
private MessageImplementation currentMessage;
private UserHub userHub;
public ClientIOProcessor(ClientModelDistributor _assignedModelDistributor, ObjectInput _socketInput,
ObjectOutput _socketOutput) {
this.assignedModelDistributor = _assignedModelDistributor;
this.socketInput = _socketInput;
this.socketOutput = _socketOutput;
assignedModelDistributor.getInputHandler().registerInputListener(this);
keepRunning = true;
}
public ClientIOProcessor(ClientLoginProcessor clientLoginProcessor, UserHub userHub) {
assignedModelDistributor = clientLoginProcessor.assignedModelDistributor;
socketInput = clientLoginProcessor.socketInput;
socketOutput = clientLoginProcessor.socketOutput;
assignedModelDistributor.getInputHandler().registerInputListener(this);
assignedModelDistributor.getIncomingMessageHandler().addIncomingMessageListener(userHub);
keepRunning = true;
this.userHub = userHub;
}
public void run() {
while (keepRunning) {
currentMessage = null;
currentMessage = buildMessageFromInput();
if(currentMessage == null) return;
switch (currentMessage.getMessageType()) {
case CHATMSG:
assignedModelDistributor.getIncomingMessageHandler().enterMessage(currentMessage);
break;
case USRJOINED:
assignedModelDistributor.getIncomingMessageHandler().enterMessage(currentMessage);
break;
case USRLEFT:
assignedModelDistributor.getIncomingMessageHandler().enterMessage(currentMessage);
break;
case TERMINATE:
this.terminateConnection();
break;
default:
System.out.println("An error occurred.");
}
}
}
public void terminateConnection() {
keepRunning = false;
assignedModelDistributor.getIncomingMessageHandler().removeIncomingMessageListener(this.userHub);
assignedModelDistributor.getInputHandler().removeInputListener(this);
try {
socketInput.close();
socketOutput.close();
} catch (IOException e) {
e.printStackTrace();
}
// System.exit(0);
}
private MessageImplementation buildMessageFromInput() {
MessageImplementation messageSentByServer = null;
try {
messageSentByServer = (MessageImplementation) socketInput.readObject();
} catch (ClassNotFoundException | IOException e) {
e.printStackTrace();
}
return messageSentByServer;
}
/**
* This method can be used to send <code>messages</code> to the server.
*
* #param message
* #throws IOException
*/
public void send(Message message) throws IOException {
try {
socketOutput.writeObject(message);
socketOutput.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* This method is called whenever the user enters input to this
* <code>InputListener</code>'s corresponding <code>InputHandler</code>.
*/
#Override
public void inputEntered(String input) {
try {
send(assignedModelDistributor.buildUserMessage(input));
} catch (IOException e) {
e.printStackTrace();
}
}
}
the clientIO processor gets the TERMINATE message from the server and calls the terminateConnection() Method to end the Streams.
Here is the ServerIOProcessor:
public class ServerIOProcessor implements Runnable, IncomingMessageListener {
private ServerModelDistributor assignedModelDistributor;
private User assignedUser;
private boolean keepRunning;
private ObjectInputStream socketInput;
private ObjectOutputStream socketOutput;
private MessageImplementation currentMessage;
private final String SYSTEM = "System";
public ServerIOProcessor(User _assignedUser, ObjectOutputStream _socketOutput, ObjectInputStream _socketInput,
ServerModelDistributor _assignedModelDistributor) {
assignedUser = _assignedUser;
socketInput = _socketInput;
socketOutput = _socketOutput;
assignedModelDistributor = _assignedModelDistributor;
keepRunning = true;
assignedModelDistributor.getIncomingMessageHandler().addIncomingMessageListener(this);
}
public void run() {
while (keepRunning) {
currentMessage = null;
currentMessage = buildMessageFromInput();
switch (currentMessage.getMessageType()) {
case CHATMSG:
assignedModelDistributor.getIncomingMessageHandler().enterMessage(currentMessage);
break;
case NEWTASK:
createNewTask();
break;
case TASKASSGNMNT:
assignTaskToUser();
break;
case NEWLEADER:
determineLeaderOfTeam();
break;
case ADDTEAM:
addTeam();
break;
case RMVTEAM:
removeTeam();
break;
case ADDTEAMMEMBER:
addUserToTeam();
break;
case RMVTEAMMEMBER:
removeUserFromTeam();
break;
case JOINTEAM:
joinTeam();
break;
case LEAVETEAM:
leaveTeam();
break;
case EDITDETAILS:
editUserDetails();
break;
case TERMINATE:
assignedModelDistributor.getIncomingMessageHandler().enterMessage(currentMessage);
letClientLeaveServer();
break;
default:
send(newSystemMessage(MessageType.ERROR));
System.out.println("An error occured in one of the server's active IO processes.");
break;
}
}
}
private void createNewTask() {
}
private void assignTaskToUser() {
// TODO Auto-generated method stub
}
private void determineLeaderOfTeam() {
// TODO Auto-generated method stub
}
private void addTeam() {
// TODO Auto-generated method stub
}
private void removeTeam() {
// TODO Auto-generated method stub
}
private void addUserToTeam() {
// TODO Auto-generated method stub
}
private void removeUserFromTeam() {
// TODO Auto-generated method stub
}
private void joinTeam() {
// TODO Auto-generated method stub
}
private void leaveTeam() {
// TODO Auto-generated method stub
}
private void editUserDetails() {
// TODO Auto-generated method stub
}
private void letClientLeaveServer() {
// TODO Auto-generated method stub
assignedModelDistributor.getIncomingMessageHandler().removeIncomingMessageListener(this);
try {
socketInput.close();
socketOutput.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
keepRunning = false;
}
private MessageImplementation buildMessageFromInput() {
MessageImplementation messageSentByUser = null;
try {
messageSentByUser = (MessageImplementation) socketInput.readObject();
} catch (ClassNotFoundException | IOException e) {
e.printStackTrace();
}
return messageSentByUser;
}
private MessageImplementation newSystemMessage(MessageType msgtype) {
return new MessageImplementation(SYSTEM, msgtype);
}
//TODO Check expected purpose of this method.
/**
* This method is called whenever a <code>Message</code> is entered to the
* corresponding <code>IncomingMessageHandler</code>.
*/
#Override
public void messageEntered(Message message) {
// assignedModelDistributor.getIncomingMessageHandler().enterMessage(message);
try {
socketOutput.writeObject(message);
socketOutput.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* Writes the given <code>Message</code> to the Socket's
* <code>ObjectInputStream</code>.
*
* #throws IOException
*/
void send(Message message) {
try {
socketOutput.writeObject(message);
socketOutput.flush();
} catch (Exception r) {
System.out.println("Error!");
r.printStackTrace();
}
}
}
the important part here is the letClientLeaveServer() method to end the streams here as well. however, i think this is the wrong way, because i think this ends the Input/Ouput Streams for all logged in Clients.
The ServerSocket it self is initialized in another class ConnectionProcessor which starts the Socket on a given port and accepts it. then the connectionProcessor starts the serverLogInProcessor which starts a new Thread for the serverIOProcessor.
Here the ConnectionProcessor:
public class ConnectionProcessor implements Runnable {
private ServerModelDistributor assignedModelDistributor;
private boolean keepRunning;
private ServerSocket serverSocket;
private int assignedPort;
public ConnectionProcessor(int _assignedPort, ServerModelDistributor _assignedModelDistributor) {
assignedModelDistributor = _assignedModelDistributor;
assignedPort = _assignedPort;
keepRunning = true;
try {
serverSocket = new ServerSocket(assignedPort);
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void run() {
while (keepRunning) {
if(serverSocket.isClosed()) {
try {
serverSocket = new ServerSocket(assignedPort);
} catch (IOException e) {
e.printStackTrace();
}
}
try {
Socket socketCreatedForLoginProcess = serverSocket.accept();
serverSocket.close();
Thread serverLoginProcessor = new Thread(
new ServerLoginProcessor(this, socketCreatedForLoginProcess, assignedModelDistributor),
"loginProcess");
serverLoginProcessor.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

how to update my jframe in a server_client game?

I'm working on a server-client game in which I need to update client's JFrame from the server in a specific period.this is my game
The problem is that the client's JFrame does not update.to be sure,I have rendered the JFrame Submitted by the server and it's OK,but the client's JFrame does not change at all.Here's my code:
my server:
public class main implements java.io.Serializable{
static ArrayList<Socket> allsockets = new ArrayList<>();
static ArrayList<ObjectOutputStream> oos = new ArrayList<>();
static final MainFrame frame=new MainFrame();
static boolean testfirst=false;
private static final long serialVersionUID = 1L;
public static void main(String[] args) {
// TODO Auto-generated method stub
String name;
String color;
Color color1 = null;
Socket clientsocket=null;
ServerSocket serversocket=null;
PrintStream os = null;
ObjectInputStream is=null;
try{
serversocket = new ServerSocket(); // don't bind just yet
serversocket.setReuseAddress(true);
serversocket.bind(new InetSocketAddress(5555)); // can bind with reuse= true
}
catch(IOException e){
System.out.println(e);
}
while(true){
try {
clientsocket=serversocket.accept();
allsockets.add(clientsocket);
oos.add(new ObjectOutputStream(clientsocket.getOutputStream()));
is=new ObjectInputStream(clientsocket.getInputStream());
os = new PrintStream(clientsocket.getOutputStream());
try {
name =(String) is.readObject();
color=(String) is.readObject();
try {
java.lang.reflect.Field field = Class.forName("java.awt.Color").getField(color);
color1 = (Color)field.get(null);
} catch (Exception e) {
color = null;
}
player p=new player();
frame.addplayer(name, color1,p);
if(!testfirst){
testfirst=true;
new Thread(){
public void run(){
Timer timer=new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
System.out.println("timer works");
for(ObjectOutputStream os:oos){
try {
os.writeObject(frame);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}, 1, 1);
}
}.start();
}
handle h= new handle(is, frame, p);
h.start();
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
my client:
public class client implements java.io.Serializable {
static private final Lock mutex = new ReentrantLock(true);
private static final long serialVersionUID = 1L;
static double prevx =0;
static double prevy=0;
static Timer timer=new Timer();
static ObjectOutputStream os =null;
public static void main(String[]args) {
MainFrame frame=new MainFrame();
Socket clientSocket=null;
ObjectInputStream is=null;
String name;
String color;
try {
clientSocket = new Socket("localhost", 5555);
os = new ObjectOutputStream(clientSocket.getOutputStream());
is=new ObjectInputStream(clientSocket.getInputStream());
System.out.println("enter your name:");
Scanner in1=new Scanner(System.in);
name=in1.nextLine();
System.out.println("enter your color:");
color=in1.nextLine();
in1.close();
os.writeObject(name);
os.writeObject(color);
refresh ref=new refresh( is, os);
ref.start();
} catch (UnknownHostException e) {
System.err.println("Don't know about host");
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to host");
}
}}
the refresh class(which has the responsibility to update client's JFrame)
public class refresh extends Thread{
MainFrame frame;
ObjectInputStream ois;
ObjectOutputStream oos;
Timer timer=new Timer();
double prevx,prevy;
private Lock mutex = new ReentrantLock(true);
public refresh(ObjectInputStream ois,ObjectOutputStream oos){
frame=new MainFrame();
this.ois=ois;
this.oos=oos;
}
public void run(){
while(true){
try {
frame= (MainFrame) ois.readObject();
frame.repaint();
frame.removeMouseMotionListener(mml);
frame.addMouseMotionListener(mml);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setFocusable(true);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
MouseMotionListener mml=new MouseMotionListener() {
#Override
public void mouseMoved(MouseEvent arg0) {
// TODO Auto-generated method stub
mutex.lock();
try {
System.out.println("mouse moved");
oos.writeObject(arg0.getX());
oos.writeObject(arg0.getY());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mutex.unlock();
}
#Override
public void mouseDragged(MouseEvent arg0) {
// TODO Auto-generated method stub
}
};}
and if needed the handle class(which receives the mouse coordinates from the client)
public class handle extends Thread{
double prevx,prevy;
MainFrame frame;
player myplayer;
ObjectInputStream ois;
double screenwidth,screenheigth;
boolean first=false;
boolean finished = false;
static private final Lock mutex = new ReentrantLock(true);
Thread movethread = new Thread(){
public void run(){
System.out.println("movethread run");
try {
if(Math.abs(prevx-myplayer.xcenter)>1 || Math.abs(prevy - myplayer.ycenter)>1){
while(Math.abs(prevx-myplayer.xcenter)!=0
|| Math.abs(prevy - myplayer.ycenter)!=0){
if(prevx<0 || prevx>screenwidth || prevy<0 || prevy>screenheigth)break;
myplayer.movem(prevx, prevy,mutex);
frame.repaint();
System.out.println(myplayer.cp.getCenter());
}
finished = true;
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}};
public handle(ObjectInputStream ois,MainFrame frame,player p) {
// TODO Auto-generated constructor stub
this.myplayer=p;
this.ois=ois;
this.frame=frame;
this.screenwidth=frame.getscreenwidth();
this.screenheigth=frame.getscreenheigth();
}
public void run(){
System.out.println("handle thread run");
while(true){
try {
System.out.println("in handle");
System.out.println(first);
prevx= (double) ois.readObject();
prevy=(double) ois.readObject();
if(!first){
System.out.println("movethread started");
movethread.start();
first = true;
}
else if(first && finished){
movethread.run();
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void update(double x,double y){
this.prevx=x;
this.prevy=y;
}}
Any help would be appreciated.

Even ,odd and evenodd consumer- producer

What I want to do here is to print even numbers by even consumers, odd numbers by odd consumers.
There is an evenodd method which is basically consuming any number and printing (whether even or odd). I have got 2 even consumer threads, 2 odd consumer threads, 2 evenodd consumer threads and 3 producer threads.
I am new to the semaphores concept, and I tried using it. When I remove the evenodd method and related threads I get the correct output i.e. Even numbers by even threads and odd numbers by odd threads. But when I again put the evenodd method and evenodd threads I get a deadlock.
It would be very helpful if anyone can guide me on this, where I am going wrong and how to fix it. Please throw some light on how I can implement the evenodd method so that it would work correctly.
package lab61;
import java.util.LinkedList;
import java.util.Random;
import java.util.concurrent.Semaphore;
public class Process {
Semaphore empty;
Semaphore full;
Semaphore even;
Semaphore odd;
Semaphore mutex;
//Semaphore evenodd;
boolean evenb;
boolean oddb,eo;
LinkedList<Integer> list;
Random random;
public Process(int capacity){
list=new LinkedList<Integer>();
empty=new Semaphore(capacity);
full=new Semaphore(0,true);
mutex=new Semaphore(1,true);
even=new Semaphore(0,true);
evenb=false;
oddb=false;
eo=false;
odd=new Semaphore(0,true);
//evenodd = new Semaphore(0,true);
random=new Random();
}
public void Producer() throws InterruptedException{
while(true){
int a=random.nextInt(100);
empty.acquire();
mutex.acquire();
list.add(a);
System.out.println("Producing "+a);
System.out.println(list);
if((list.get(0)%2)==0){
if(!evenb){
even.release();
evenb = true;
}
}else if((list.get(0)%2)==1){
if(!oddb){
odd.release();
oddb = true;
}
}
/*if(((list.get(0)%2)==0)||((list.get(0)%2)==1)){
if(!eo){
evenodd.release();
eo = true;
}
}*/
mutex.release();
full.release();
}
}
public void consumereven() throws InterruptedException{
while(true){
//Thread.sleep(2000);
even.acquire();
Thread.sleep(2000);
full.acquire();
mutex.acquire();
int value = list.removeFirst();
System.out.println("I am the even consumer "+ value);
evenb = false;
System.out.println(list);
mutex.release();
empty.release();
}
}
public void consumerodd() throws InterruptedException{
while(true){
//Thread.sleep(2000);
odd.acquire();
Thread.sleep(2000);
full.acquire();
//odd.acquire();
mutex.acquire();
int value = list.removeFirst();
System.out.println("I am the odd consumer "+ value);
System.out.println(list);
oddb = false;
mutex.release();
empty.release();
}
}
public void evenodd() throws InterruptedException {
while(true){
full.acquire();
mutex.acquire();
int value = list.removeFirst();
System.out.println("i am the evenodd consumer " + value );
if((list.get(0)%2)==0){
if(oddb=true){
odd.acquire();
oddb=false;
}
if(evenb==false){
even.release();
evenb = true;
}
}
else if((list.get(0)%2)==1){
if(evenb=true){
even.acquire();
evenb=false;
}
if(oddb==false){
odd.release();
oddb = true;
}
}
System.out.println(list);
mutex.release();
empty.release();
}
}
}
package lab61;
import lab6.producer;
public class App {
public static void main(String[] args) throws InterruptedException{
Process p=new Process(10);
Thread producer1=new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
p.Producer();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Thread producer2=new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
p.Producer();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Thread producer3=new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
p.Producer();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Thread consumereven1=new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
p.consumereven();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Thread consumereven2=new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
p.consumereven();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Thread consumerodd1=new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
p.consumerodd();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Thread consumerodd2=new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
p.consumerodd();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Thread evenodd1=new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
p.evenodd();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Thread evenodd2=new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
p.evenodd();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
producer1.start();
producer2.start();
producer3.start();
consumereven1.start();
consumereven2.start();
consumerodd1.start();
consumerodd2.start();
evenodd1.start();
evenodd2.start();
producer1.join();
producer2.join();
producer3.join();
consumereven1.join();
consumereven2.join();
consumerodd1.join();
consumerodd2.join();
evenodd1.join();
evenodd2.join();
}
}
The code can cause a deadlock because consumereven() and consumerodd() methods acquire the even or odd semaphore before the full and mutex semaphores, while the evenodd() method acquires the full and mutex semaphores before the even or odd semaphore. This results in a situation where, say, a thread running consumereven() has the even semaphore but is blocked while waiting on the full semaphore, while a thread running evenodd() has the full semaphore, but is blocked on the even semaphore, so the two threads are deadlocked.
To help prevent deadlocks, when you use multiple locks, it's best always to acquire them in the same order wherever they are used, and release them in the reverse order of acquisition.
Not a Great way of doing it but u could do something like.
import java.util.LinkedList;
import java.util.Random;
import java.util.concurrent.Semaphore;
public class P1 {
Semaphore empty;
Semaphore full;
Semaphore even;
Semaphore odd;
Semaphore mutex;
Semaphore oddeven;
LinkedList<Integer> list;
Random random;
boolean oddb;
boolean evenb;
boolean oddevenb;
public P1(int capacity){
list=new LinkedList<Integer>();
empty=new Semaphore(capacity,true);
full=new Semaphore(0,true);
mutex=new Semaphore(1,true);
even=new Semaphore(0,true);
odd=new Semaphore(0,true);
oddeven=new Semaphore(0,true);
oddb=false;
evenb=false;
oddevenb = false;
random=new Random();
}
public void Producer(String s) throws InterruptedException{
while(true){
int a=random.nextInt(100);
empty.acquire();
mutex.acquire();
list.add(a);
System.out.println("Producing "+a+" By "+s);
System.out.println(list);
int temp=random.nextInt(3)+1;
if(temp==1 ){
if(oddevenb==false){
oddeven.release();
oddevenb=true;
evenb=true;
oddb=true;
}
}
else{
if((list.get(0))%2==0){
if(evenb==false){
even.release();
evenb=true;
oddevenb=true;
}
}else if((list.get(0))%2==1){
if( oddb==false) {
odd.release();
oddevenb=true;
oddb=true;
}
}
}
mutex.release();
full.release();
}
}
public void consumereven(String s) throws InterruptedException{
while(true){
// Thread.sleep(5000);
even.acquire();
full.acquire();
mutex.acquire();
int value=list.removeFirst();
System.out.println("I am the "+ s +" consumer "+value);
evenb=false;
oddevenb=false;
System.out.println(list);
mutex.release();
empty.release();
}
}
public void consumerodd(String s) throws InterruptedException{
while(true){
//Thread.sleep(5000);
odd.acquire();
full.acquire();
mutex.acquire();
int value= list.removeFirst();;
System.out.println("I am the "+s+" consumer "+value);
oddb=false;
oddevenb=false;
System.out.println(list);
mutex.release();
empty.release();
}
}
public void consumeroddeven(String s) throws InterruptedException{
while(true){
//Thread.sleep(5000);
oddeven.acquire();
full.acquire();
mutex.acquire();
int value= list.removeFirst();;
System.out.println("I am the "+s+" "+value);
System.out.println(list);
oddevenb=false;
evenb=false;
oddb=false;
mutex.release();
empty.release();
}
}
}
public class App3 {
public static void main(String[] args) throws InterruptedException{
final P1 p=new P1(10);
Thread producer=new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
p.Producer("p1");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Thread producer2=new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
p.Producer("p2");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Thread producer3=new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
p.Producer("p3");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
},"p3");
Thread consumereven=new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
p.consumereven("even1");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Thread consumereven2=new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
p.consumereven("even2");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Thread consumerodd=new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
p.consumerodd("odd1");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Thread consumerodd2=new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
p.consumerodd("odd2");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Thread consumer=new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
p.consumeroddeven("NC1");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Thread consumer1=new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
p.consumeroddeven("NC2");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
producer.start();
producer2.start();
producer3.start();
consumereven.start();
consumereven2.start();
consumerodd.start();
consumerodd2.start();
consumer.start();
consumer1.start();
producer.join();
producer2.join();
producer3.join();
consumereven.join();
consumereven.join();
consumereven2.join();
consumerodd.join();
consumerodd.join();
consumerodd2.join();
consumer.join();
consumer1.join();
}
}

Java: Server not receiveing messages over tcp socket more than once.

A Client(botnet server) is trying to send continuous messages over TCP socket to a server(disruptor), but only one message is received at the disruptor. Disruptor is a thread which is created by the botnet server.
code: Botnet server
public static void main(String[] args) {
// TODO Auto-generated method stub
Jedis jedis = new Jedis("localhost");
String pattern = new String("TKproject");
input = new Disruptor(30001,1024,jedis,pattern);
int count = 0;
Thread start = new Thread(input);
start.start();
try {
request = new Socket("localhost",30001);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Random rand = new Random();
Message msg = new Message();
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(request.getOutputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while(true){
System.out.println("count is : " + count);
count++;
if(count == 5)
break;
if(count % 15 == 0)
jedis.rpush(pattern,Integer.toString(count));
int next = rand.nextInt(3);
msg.setMessageId(count);
switch (next){
case 0: msg.setType(MessageType.HELLO);
break;
case 1: msg.setType(MessageType.REQUEST);
break;
case 2: msg.setType(MessageType.REPLY);
break;
default: msg.setType(MessageType.REQUEST);
break;
}
//System.out.println("Message id "+msg.Messageid);
try {
oos.writeObject(msg);
//oos.flush();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Disruptor run()
public void run() {
// TODO Auto-generated method stub
while(true){
System.out.println("Disruptor Running");
Socket receipt = null;
try {
receipt = server.accept();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ObjectInputStream recv = null;
try {
recv = new ObjectInputStream(receipt.getInputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*
byte [] rcvbytes = new byte[2048];
try {
recv.read(rcvbytes);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
try {
storage.write((Message)recv.readObject());
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
receipt = server.accept();
You need to perform this just once to connect your server to a client, try and move that instruction before the while(true).
The same needs to be done for the ObjectInputStream declaration.
Either:
send a new Message object each time instead of refreshing the old one
send it using `writeUnshared()’, or
call ObjectOutputStream.reset() before sending a refreshed Message object.

Categories