How to control Windows from Android Keyboard? - java

I created the mobile app on client side for Android successfully.
Then Server side, that is windows server code also created. I can able to type all the letters numbers and all.
My problem is using shift key and "#" key. I need "#" into my project. When I press the "#" crashes the connection and says...
Invalid key code
at sun.awt.windows.WRobotPeer.keyPress(Native Method)
at java.awt.Robot.keyPress(Unknown Source)
at pcHotkey.keyboardServer$Capitalizer.run
Now, how should I type "#" with my app. Then I press shift key it was passing correctly and it was not stopping the pressed state.
My code goes here,
1st class:
aMap.put("Shift", KeyEvent.VK_SHIFT);
aMap.put("At", KeyEvent.VK_AT);
try{
robo = new Robot();
}
catch(Exception e)
{}
ServerSocket listener = new ServerSocket(9898);
try {
while (true) {
new Capitalizer(listener.accept(), clientNumber++).start();
}
} finally {
listener.close();
}
2nd class :
public Capitalizer(Socket socket, int clientNumber) {
this.socket = socket;
this.clientNumber = clientNumber;
log("New connection with client# " + clientNumber + " at " + socket);
}
public void run() {
try {
BufferedReader in = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
// Send a welcome message to the client.
out.println("Hello, you are client #" + clientNumber + ".");
out.println("Enter a line with only a period to quit\n");
while (true) {
String input = in.readLine();
System.out.println(input);
if(input.equals("Caps")){
Toolkit.getDefaultToolkit().setLockingKeyState(KeyEvent.VK_CAPS_LOCK, true);
;
}
else if(input.equals("At"))
{
log("Log Value : "+ input);
//Toolkit.getDefaultToolkit().setLockingKeyState(KeyEvent.VK_SHIFT, true);
robo.keyPress(aMap.get("At"));
//Toolkit.getDefaultToolkit().setLockingKeyState(KeyEvent.VK_SHIFT, true);
}
else
robo.keyPress(aMap.get(input));
}
} catch (IOException e) {
log("Error handling client# " + clientNumber + ": " + e);
} finally {
try {
socket.close();
} catch (IOException e) {
log("Couldn't close a socket, what's going on?");
}
log("Connection with client# " + clientNumber + " closed");
}

I did by passing the keycode of "SHIFT" and "2". Problem got fixed now.

Related

how to stop a process when "ctrl+c" is pressed in java?

i am using the following in one of my application.
public static void concatenation(List<String> commands) throws IOException {
if (commands.get(1).equals(">")) {
String path = history.getFilePath();
File file = new File(path + "\\" + commands.get(2));
if (file.exists() && file.isFile()) {
try (FileWriter writer = new FileWriter(file)) {
Scanner scanner = new Scanner(System.in);
String line;
System.out.println("Write to file. Press Ctrl+C to stop.");
while (true) {
try {
line = scanner.nextLine();
writer.write(line + System.lineSeparator());
writer.flush();
} catch (Exception e) {
System.out.println("Interrupted. Stopping...");
break;
}
}
scanner.close();
} catch (IOException e) {
System.out.println("Error writing to file: " + e.getMessage());
}
}
} else {
System.out.println("bash : " + commands.get(1) + " : unrecognized operator");
}
}
i want to exit out of the while loop when ctrl + c is pressed. And it is a console application. How to achieve this?

Why are the last two instructions unreachable code?

Eclipse spots them as unreachable code, which apparently is a code that will never be read for there's no path to reach it, but I don't see why. The instructions are inside a main() method
//leemos
FileInputStream fis;
ObjectInputStream ois;
Alumno alumnoLeido = null;
String cadena ="";
JTextArea area = new JTextArea(6,1);
while(true){
try {
fis = new FileInputStream("alumnos.txt");
ois = new ObjectInputStream(fis);
alumnoLeido = (Alumno) ois.readObject();
ois.close();
cadena = "Alumno " + alumnoLeido.getNombre() + " " + alumnoLeido.getApellido() + " vive en "
+ alumnoLeido.getDireccion() + " y tiene una beca de " + alumnoLeido.getBeca() + " euros \r\n";
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
area.append(cadena);
JOptionPane.showMessageDialog(null, area, "Alumnos",1);
while(true) is an infinite loop. Without a break, the loop will never terminate and allow the following code to execute. So, you will never reach the remaining statements.
They are unreachable because your while loop will never terminate.

Sending email through program

I am trying to write a program using java that will send an email. I am using JDK 1.6.0_43
I am getting java.net.UnknownHostException: mailhost error. My code is as follows -
import java.io.*;
import java.net.*;
public class SendMail {
public static void main(String[] args) {
try {
if (args.length >= 1)
System.getProperties().put("mail.host", args[0]);
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("From: ");
String from = in.readLine();
System.out.print("To: ");
String to = in.readLine();
System.out.print("Subject: ");
String subject = in.readLine();
URL u = new URL("mailto:" + to);
URLConnection c = u.openConnection();
c.setDoInput(false);
c.setDoOutput(true);
System.out.println("Connecting...");
System.out.flush();
c.connect();
PrintWriter out = new PrintWriter(new OutputStreamWriter(c.getOutputStream()));
out.println("From: \"" + from + "\" <" + System.getProperty("user.name") + "#" + InetAddress.getLocalHost().getHostName() + ">");
out.println("To: " + to);
out.println("Subject: " + subject);
out.println();
System.out.println("Enter the message. " + "End with a '.' on a line by itself.");
String line;
for(;;) {
line = in.readLine();
if ((line == null) || line.equals("."))
break;
out.println(line);
}
out.close();
System.out.println("Message sent.");
System.out.flush();
}
catch (Exception e) {
System.err.println(e);
System.err.println("Usage: java SendMail [<mailhost>]");
}
}
}
How to solve this?
The error message says it all: Usage: java SendMail [<mailhost>]
You need to know the name (or IP address) of your mail server. So try executing it like this:
java SendMail smtp.example.com

Reading And Writing to text file

I've written this code to read in a file and then ask for a mark, for each name in the file. And if the mark is over 40 its a pass and below is a fail and writes each name to the corresponding file. But I get an error at line 27 which: while(namesFile.hasNext() here's my code:
import java.io.*;
import java.util.*;
public class TestResults {
public static void main(String[] args) {
String errs = "";
Scanner k = new Scanner(System.in);
try {
try (
Scanner namesFile = new Scanner(new File("Names.txt"));
PrintWriter passFile = new PrintWriter("Pass.txt");
PrintWriter failFile = new PrintWriter("Fail.txt");) {
while (namesFile.hasNext()) {
try {
String tempLine = namesFile.nextLine();
System.out.println("Please Enter Mark For " + tempLine + " : ");
int mark = k.nextInt();
if (mark >= 40) {
passFile.println(tempLine + " " + mark + "%");
} else {
failFile.println(tempLine + " " + mark);
}
} catch (InputMismatchException ime) {
String valueStr = namesFile.next();
errs += "\n\t" + valueStr;
} finally {
namesFile.close();
passFile.close();
failFile.close();
}
}
}
} // Checks to see if file is there.
catch (IOException ioe) {
System.out.println("ERROR: " + ioe.getMessage());
}
}
}
public class TestResults {
public static void main(String[] args) {
Scanner namesFile;
PrintWriter passFile;
PrintWriter failFile;
String errs = "";
Scanner k = new Scanner(System.in);
try {
try {
namesFile = new Scanner(new File("D:/Names.txt"));
passFile = new PrintWriter("D:/Pass.txt");
failFile = new PrintWriter("D:/Fail.txt");
try {
while (namesFile.hasNext()) {
String tempLine = namesFile.nextLine();
System.out.println("Please Enter Mark For " + tempLine + " : ");
int mark = k.nextInt();
if (mark >= 40) {
passFile.println(tempLine + " " + mark + "%");
} else {
failFile.println(tempLine + " " + mark);
}
}
} catch (InputMismatchException ime) {
String valueStr = namesFile.next();
errs += "\n\t" + valueStr;
} finally {
namesFile.close();
passFile.close();
failFile.close();
}
}
catch(IOException ioe){
System.out.println("ERROR: " + ioe.getMessage());
}
} // Checks to see if file is there.
catch (Exception e) {
}
}
}

NoSuchElementException when setting a timeout on the socket

I wanted to set a timeout when a client read. the routine supposed to throw an InterruptedIOException but instead it throws NoSuchElementException on System.out.println("echo: " + _in.nextLine()); what am I doing wrong ?
this is my methode
public void startUserInput()
{
try {
_out = new PrintWriter(_echoSocket.getOutputStream(), true);
_in = new Scanner(new InputStreamReader(_echoSocket.getInputStream()));
Scanner stdIn = new Scanner(new InputStreamReader(System.in));
System.out.print("Input: ");
while (stdIn.hasNextLine()) {
_out.println(stdIn.nextLine());
System.out.println("echo: " + _in.nextLine());
System.out.print("Input: ");
}
stdIn.close();
}catch (InterruptedIOException exception){
System.err.println("The server is not responding " + _serverHostname);
}
catch (IOException e) {
System.out.println("error" + e.getLocalizedMessage());
}}
and this is my connection
public boolean establishConnection()
{
System.out.println ("Connecting to the host " +
this.getServerHostname() + " au port " + this.getServerPort());
try {
_echoSocket = new Socket();
_echoSocket = new Socket(this.getServerHostname(), this.getServerPort());
_echoSocket.setSoTimeout(10000);
System.out.println(_echoSocket.getOutputStream());
return _echoSocket.isConnected();
} catch (UnknownHostException e) {
System.err.println("Unknown host: " + this.getServerHostname());
return false;
} catch (IOException e) {
System.err.println("Error while connecting to the server : " +
this.getServerHostname() + ":" + this.getServerPort());
return false;
}
}
Thanks
The reason is that when you invoked _in.nextLine() there is no line to be read in from the from the Scanner object _in.
What you did in the while loop was to check for stdIn.hasNextLine() but you did not check if _in has a nextLine() that can be read.
For details on the exception, you can check out:
http://download.oracle.com/javase/1,5.0/docs/api/java/util/Scanner.html#nextLine()
hope it helps :) Cheers!

Categories

Resources