VT100 and Processing, getting cursor position - java

i'm trying to implement a telnet interface in a Processing sketch, to pass command and receive outputs on the console.
I'm learning those days about the VT100 set of commands, so i was finally able to understand how was possible to reprint on already printed strings by moving the cursor.
I saw that it is also possible for the program to get input from the console, like with the Get cursor position command.
myClient.write("\033]6n"); //^[6n
The problem is that just print on the client interface the position, while i would like to have it back on the host. Someone know if and how is this possible?
Thank you
Here some example code:
import processing.net.*;
Server myServer;
void setup() {
myServer = new Server(this, 10002); // Starts a myServer on port 10002
}
void draw() {
Client thisClient = myServer.available();
if (thisClient != null) {
if (thisClient.available() > 0) {
String recived = thisClient.readString();
println(recived);
thisClient.write("\033[2A\r\033[2K" + "You just wrote: " + recived + "\033[2K");
thisClient.write("\033[6n"); // this happear on the client side, i want it back somehow
}
}
}
void serverEvent(Server someServer, Client someClient) {
someClient.write("\nhello, type something please...\n");
}

Related

Deleting text from the console in java

I'm making a console chat application and now I have some problems with displaying messages on the client program.
My client program has two threads a read thread and write thread. The read thread gets messages from the server and write sends messages. The write thread has a Console object reading one line with a some text indicating to the user where to write your message. It looks like this in the console:
[Username]: message goes here
And this works fine when you only want to send messages, but I also have a read thread which is receiving and displaying messages that it got from the server. Which messes up this whole input thing because for example when the read thread gets a message it just prints it to the console and then prints another indicator on the next line and then everything looks like this:
[Username]:
[qwerty]: hello
[Username]:
I tried deleting the first indicator by printing \b (backspace) escape character in a for loop that looks like this:
String username = "username";
String indicator = "[" + username + "]: ";
for (int i = 0; i < indicator.length(); i++)
{
System.out.print("\b");
}
It worked on regular text, but not on the indicator. I think that's because the Console object reading for input in the same line somehow gets in the way.
This problem is even worse when the user is typing out a message and in the middle of the typing the user gets a message this happens:
[Username]: Hel //the user wanted to type out hello but got cut off
[qwerty]: hello
[Username]:
If the user where to finish writing hello on the next line and then send it. For the other client the message would say hello with no sign that the clients writing was interrupted by him, but for the client writing the message it would look like it sent two separate messages. I don't know how to fix this at all. Any help is appreciated.
Code for write thread:
public static class write implements Runnable
{
public void run()
{
Console cons = System.console();
while (true)
{
username = "[dgsgsdfg]: ";
System.out.print(username);
String input = cons.readLine();
String msg = username + input;
System.out.println(msg);
}
}
}
Code for read thread:
public static class read implements Runnable
{
public void run()
{
try
{
while(true)
{
Thread.sleep(5000);
for (int i = 0; i < username.length(); i++)
{
System.out.print("\b");
}
System.out.println("\n[qwerty]: hello");
System.out.print("[dgsgsdfg]: ");
}
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
P.S: The code show here is from a different program I created to try and fix this problem and it only contains the text printing part, and no networking or server stuff. The writer thread every 5 seconds prints hello, to simulate receiving and displaying a message.

Read Complete Line Java Serial Port

I have implmented JSSC API so I can communicate with the Com Port.
I send a command like "N\r\n"
and what i receive in a normal hyperterminal should look like this:
0100071CA79215021803164442180000
0100071C9F5415021803164514520000
0100071CDF5115022106142956600000
NOK
But when i do the same with the JSSC API i receive this (only the first code)
010
0071CA79
2150218
0316444
218
The Problem is that i randomly receive bit parts and at the end of the code i lose some parts. But thats not important i only need the first 12 digits of every code.
The Question is now how do i get the function to only receive the full line and not bitparts?
This is the receiving part of the class
class PortReader2 implements SerialPortEventListener {
#Override
public void serialEvent(SerialPortEvent event) {
if(event.isRXCHAR()&& event.getEventValue() > 2) {
try {
// получение ответа от порта
String receivedData = serialPort.readString();
System.out.println(receivedData.length() + ":" + receivedData);
}
catch (SerialPortException ex) {
System.out.println("Error in receiving response from port: " + ex);
}
}
}
}
This is the sending part
public void sendCodeCommand(SerialPort serialPort) {
// writing string to port
try {
Thread.sleep(3000);
serialPort.writeBytes("N\r\n".getBytes());
} catch (SerialPortException | InterruptedException ex) {
Logger.getLogger(ComPortSendReceive.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("String wrote to port, waiting for response..");
}
To fix the stated problem you need to concatenate the strings you receive into another string that accumulates the string fragments you receive from the readString() function, which is in the serialEvent handler. Because it is it's owm thread it gets a certain amount of cpu time to get serial data so it effectively gets partial sequential reads of the serial port input data. So this example puts the partial inputs together to create the "whole" input.
String serialString;
So within the serialEvent handler:
try {
serialStringFragment = serialPort.readString();
serialString.concat(serialStringFragment);
}
Either the string you get from readString() or the accumulation string can be scanned for tokens like eol condition. For Example:
String [] dlLines = serialString.split("\r\n");
will break each line out to an element in the dlLines string array.
However I have found that if I have fixed length output from my target device this works better:
serialPort.readString(int bytecount);
inline with the write serial string, eliminating the serialEvent handler.
This is a bit contrived but In other words:
String expectedStringLength "0100071CA79215021803164442180000";
int serialstrlen = expectedStringLength.length();
So the serialstrlen should obviously become constants for each expected line.
serialPort.writeString("N\r\n");
serialPort.readString(serialstrlen+2); // assuming cr lf
should get you the first line.
Put the readString() in a loop, change serialstrelen argument value according to the expected strings. Check the strings for alternate content for error handling. This has worked for me.

Ping function returns that all pinged IP addresses is reachable

I am tring to ping IP addresses from 192.168.1.1 to 192.168.1.254. First I was using I InetAddress class but it was bugged and some IPs where not reachable even if they are. After that I tried this method and it worked very well for single ping IP but when I put it inside for-loop all pinged IPs where reachable... Can you guys tell me what's wrong here?
CODE:
public class Main {
public static void main(String[] args) {
String ip="192.168.1.";
try
{
for(int i=0;i<=254;i++){
String ip2=ip+i;
boolean reachable = (java.lang.Runtime.getRuntime().exec("ping -n 1 "+ip2).waitFor()==0);
if(reachable){
System.out.println("IP is reachable:: "+ip2);
}
else{
System.out.println("IP is not reachable: "+ip2);
}
}
}catch(Exception e)
{
e.printStackTrace();
}
}
}
EDIT 1:
I used built in Java function to preform pinging but it's not working (again)
here is code that I used
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class Test {
public static void main(String[] args) throws UnknownHostException, IOException {
String ip = "192.168.1.243";
InetAddress inet = InetAddress.getByName(ip);
System.out.println("Sending Ping Request to " + ip);
if (inet.isReachable(5000)){
System.out.println(ip+" is reachable");
}
else{
System.out.println(ip+" is not reachable");
}
}
}
OUTPUT IS:
Sending Ping Request to 192.168.1.243
192.168.1.243 is not reachable
Also here is ping result when I do pinging from Windows 7 built in Ping function (cmd)
Use isReachable() instead.
InetAddress.getByName(address).isReachable(timeout);
Why it does not work:
You are using the exit status of the ping process, not the actual result of the ping itself. It will just tell you whether or not the process exited normally or not. A failed ping does not cause the process to exit abnormally, and thus an exit code of 0 (zero) is always returned.
What you could try instead:
Get the output stream of the process, which will tell you what the output is. Then try to interpret/parse this however you would like:
http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Process.html#getOutputStream%28%29
(Although this also doesn't feel perfect for me, it is a much better choice than using the exit code)
Dear sir The issue why you program cannot ping systems over the loop is, the execution of the loop is faster compared to the replies from the systems.That is why some of them replies Unreachable, in order to solve such problem you are supposed to use a thread and introduce a little delay on each ping by using Thread.sleep() method.I think this will work Thank you

Chat Server - client/server chat Java homework

My chat room program. I have 2 packages, 1 for Client & other for Server. Run Server program, fill the PortField and click button Start Server, window program is stuck, i cant do anything on it, but Server still work, Clients still connect and chat.
private void btnOpenActionPerformed(java.awt.event.ActionEvent evt) {
int port = Integer.parseInt(txtPort.getText());
go(port);
}
private void go(int port){
try {
listUser = new Hashtable<String, ClientConnect>();
server = new ServerSocket(port);
txaStatus.append("Server is started\n");
txaStatus.append("IP Server : "+InetAddress.getLocalHost().getHostAddress()+"\n");
txaStatus.append("Port : " + port + "\n");
while(true){
client = server.accept();
new ClientConnect(this,client);//class ClientConnect for DataOutPut & DataInput Client <=> Server
}
} catch (IOException e) {
txaStatus.append("Server cannot start\n");
JOptionPane.showMessageDialog(this,"Port busy","warning",JOptionPane.WARNING_MESSAGE);
System.exit(0);
}
}
You can't run your server in the GUI Thread, this will prevent the program from accepting any other input. You need to move the go() method into a separate thread.
I'd say it's safe to assume that you've already been introduced to multi-threading, given the nature of this assignment. This sounds like a good time to try some of that.

Android client/Java server socket; android sending but not receiving?

I've been searching for four hours and this is driving me nuts. I'm going to try keeping this short, if you need more information/code ask and I'll edit.
So I have an Android client that connects to a server using PrintWriter and BufferedReader. The way it works is it starts a new ASyncTask() to load the connection. When the connection is made, it sends a "Join" message to the server, and then loads a listen thread that has a while loop waiting for UserInput.readLine() != null, and once broken it returns a string that runs a process function that takes the string and does it's action, and reloads the listen task.
//Listener thread
class listen extends AsyncTask<Integer, Integer, Void> {
#Override
protected Void doInBackground(Integer... params) {
//Disconnect variable that's only turned true on backpress
if (!disconnect) {
try {
message = Connection.listen(); //socket object
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// async task finished
if (!disconnect) {
say("INCOMMING"); //easy-made function for Toast
input(message);
}
}
}
and in that Connection:
public String listen() throws IOException {
String userInput;
while ((userInput = in.readLine()) != null) {
}
return userInput;
}
Now in my server java app, I have a thread that loads up other connection threads into an ArrayList and acts as a headquarters to dispatch messages to all child clients
In my connection:
while ((inputLine = in.readLine()) != null) {
//Tells HQ to process string, with id being who it's coming from
hq.Process(id, inputLine);
if (!connected)
break;
}
in HQ object:
public void Process(int id, String str) {
String[] msg = str.split(","); //split message
String send = " "; //string I print to console
if (msg[0].equals("join")) {
send = msg[1] + " has joined!";
parent.seats[cnew.get(id).seat] = id;
cnew.get(id).sendData();
System.out.println(id);
}
And after join, the HQ tells that connection to send that player's information to the phone
public void sendData() {
out.println("chips," + chips); // Update chip count
//give player his cards
out.println("card," + hq.parent.gameCards.getCard(10) + ","
+ hq.parent.gameCards.getCard(11));
//a cry for help to get some output on the phone
out.println("error,SAY THIS");
// out.flush(); //commented out because it didn't help at all
System.out.println("sending id " + id); //debug checker (ignore this)
}
My problem is, it worked when I connected four phones and they all sent toasts to each other.
But as soon as I changed it to send back data as soon as the player joins, I'm not getting a response in Android at all.
I can't figure out why it's not working. On server side, it's going through everything (Checked with system.prints). The connection IS made, and when I click buttons on the phone the Server is outputting it's responses. But the phone is not receiving anything -- I still don't know if the server is failing to send or the phone is failing to read. Can you see anything in the code that may be causing this? Need to see more? Or have any tips on how to debug the connection status? The listen() task is never finishing it's execution anymore.
UPDATE: So I figured out it's probably to do with my while() loop on android side, doh, probably never breaking. Stupid mistake. But I tried to add this as a tester, and still nothing:
public String listen() throws IOException {
String userInput;
while ((userInput = in.readLine()) != null) {
if (userInput.length() > 2)
break;
}
return userInput;
}
UPDATE: Next desperate update -
When I hit "back" (which sends quit msg to server that closes connection, and calls out.close and the rest.close) then I get a never ending loop of "MSG" Toast's -- The Toast that I put when an input is recognized. Is a out.close causing a block?
So it turns out, println on the server's side wasn't printing a new line -- adding + "\n" at the end of the server's messages made it go through. Why? I don't know..

Categories

Resources