RXTX Can't receive input signals - java

Need help,..how to send AT command and reading response using RXTX, previously i am using javax.comm and my code running very well,but i can't receive signal using RXTX,i have read this link http://rxtx.qbang.org/wiki/index.php/Two_way_communcation_with_the_serial_port but i don't know how to use it to send AT command, this is my code :
public class SendAtCommand {
Enumeration portIdentifiers = CommPortIdentifier.getPortIdentifiers();
private int indexNya;
public String sendCommand(String cmd, CommPortIdentifier portX) throws UnsupportedCommOperationException, IOException, PortInUseException {
while (true) {
try {
Thread.sleep(3000);
} catch (InterruptedException ex) {
Logger.getLogger(SendAtCommand.class.getName()).log(Level.SEVERE, null, ex);
}
if (portX == null) {
System.err.println("Could not find serial port ");
System.exit(0);
}
SerialPort port = null;
try {
port = (SerialPort) portX.open("Wavecom", 10000); // Wait max. 10 sec. to acquire port
} catch (PortInUseException e) {
System.err.println("Port already in use: " + e);
System.exit(0);
}
try {
port.setSerialPortParams(
115200,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
} catch (Exception e) {
System.out.println(e.toString());
}
BufferedReader is = null;
PrintStream os = null;
try {
is = new BufferedReader(new InputStreamReader(port.getInputStream()));
} catch (IOException e) {
System.err.println("Can't open input stream");
is = null;
}
try {
os = new PrintStream(port.getOutputStream(), true);
} catch (IOException e) {
System.err.println("Can't open output stream");
is = null;
}
os.print(cmd);
os.print("\r\n");
os.flush();
try {
cmd = is.readLine();
cmd=is.readLine();
cmd=is.readLine();
os.flush();
System.out.println(cmd);
} catch (IOException e)
{
System.err.println("Can't recieve input signals");
}
port.close();
return cmd;
}
}
public static void main(String[] args) throws NoSuchPortException, IOException, PortInUseException {
SendAtCommand sendX = new SendAtCommand();
try {
CommPortIdentifier port = CommPortIdentifier.getPortIdentifier("COM16");
String countSms = sendX.sendCommand("AT+CIMI", port);
} catch (UnsupportedCommOperationException ex) {
Logger.getLogger(SendAtCommand.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
and when i printStackTrace() i am getting this error message :
java.io.IOException: Underlying input stream returned zero bytes
at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:287)
at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:325)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:177)
at java.io.InputStreamReader.read(InputStreamReader.java:184)
at java.io.BufferedReader.fill(BufferedReader.java:154)
at java.io.BufferedReader.readLine(BufferedReader.java:317)
at java.io.BufferedReader.readLine(BufferedReader.java:382)
at mobodmt.SendAtCommand.sendCommand(SendAtCommand.java:84)
at mobodmt.SendAtCommand.main(SendAtCommand.java:108)

Related

StreamCorruptedException after ~1000 transferred objects

I want to transfer objects (AssignmentListener) from one Java Server to 5 Java Clients.
Therefore I wrote a method to send out the message:
private void sendMessage(AssignmentListener listener, int[] subpartitionIndices){
boolean success = false;
int failCount = 0;
// retry for the case of failure
while(!success && failCount < 10) {
try {
// get the stored socket & stream if stored
if(listener.getSocket() == null) {
if (localMode) {
listener.setSocket(new Socket("localhost", listener.getPort()));
} else {
listener.setSocket(new Socket(listener.getIp(), listener.getPort()));
}
listener.setOutputStream(new ObjectOutputStream(listener.getSocket().getOutputStream()));
}
AssignmentListenerMessage assignmentListenerMessage = new AssignmentListenerMessage(subpartitionIndices);
System.out.println("Sending " + assignmentListenerMessage);
listener.getOutputStream().writeObject(assignmentListenerMessage);
listener.getOutputStream().flush();
success = true;
} catch (IOException se) {
se.printStackTrace();
System.err.println("Failed to forward " + Arrays.toString(subpartitionIndices) + " to " + listener);
failCount++;
}
}
}
On the client side, I have the following:
public void run() {
String mode = "remote";
if(localMode) mode = "local";
// we need to register this listener at at the OverpartitioningManager
if(register(isLocalRequest)) System.out.println("Registered AssignmentListenerServer for index "+subpartitionIndex+" at ForwardingServer - "+mode);
running = true;
while (running) {
try {
socket = serverSocket.accept();
// Pass the socket to the RequestHandler thread for processing
RequestHandler requestHandler = new RequestHandler( socket );
requestHandler.start();
} catch (SocketException se) {
se.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
class RequestHandler extends Thread {
private Socket socket;
RequestHandler(Socket socket) {
this.socket = socket;
}
#Override
public void run() {
try {
System.out.println("Received a connection");
// Get input and output streams
inStream = new ObjectInputStream(socket.getInputStream());
//outStream = new DataOutputStream(socket.getOutputStream());
AssignmentListenerMessage incomingMessage = null;
while(socket.isBound()) {
try {
incomingMessage = (AssignmentListenerMessage) inStream.readObject();
}catch (StreamCorruptedException sce){
System.out.println("Failed to read AssignmentMessage from Stream, but will try again... (no ack)");
sce.printStackTrace();
continue;
}
// do stuff with the message
}
// Close our connection
inStream.close();
socket.close();
System.out.println("Connection closed");
} catch (Exception e) {
e.printStackTrace();
}
}
}
This works multiple times, but at one point I get the following exception:
java.io.StreamCorruptedException: invalid type code: 00
Does anyone have an idea or any other performance improvement for what I'm doing?
Thanks.

TCP client and server; cmd prompt using object streams issue [duplicate]

I have one client file clientRPC.java and server file serverRPC.java. Both communicate using TCP protocol and use objectinput and output stream to transfer data.
my client file:
public class clientRPC {
public static void main(String args[]) {
Socket s = null;
try {
int serverPort = 8888;
s = new Socket("localhost", serverPort);// server name is local host
//initializing input and output streams object and referencing them to get input and output
ObjectInputStream in = null;
ObjectOutputStream out = null;
out = new ObjectOutputStream(s.getOutputStream());
in = new ObjectInputStream(s.getInputStream());
MathsTutor mt = new MathsTutor();
out.writeObject(mt);
out.flush();
System.out.println("Welcome to Maths Tutor Service. The available maths exercises are:\n"
+ "Addition: Enter 'A' or 'a'\n"
+ "Subtraction: Enter 'S' or 's'\n"
+ "Multiplication: Enter 'M' or 'm'\n"
+ "Division: Enter 'D' or 'd'\n"
+ "Enter 'Q' or 'q' to quit");
//System.out.println();
MathsTutor mt1 = (MathsTutor) in.readObject();
String response = in.readUTF();
System.out.println(response);
} catch (UnknownHostException e) {
System.out.println("Socket:" + e.getMessage());
} catch (EOFException e) {
System.out.println("EOF:" + e.getMessage());
} catch (IOException e) {
System.out.println("readline:" + e.getMessage());
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
} finally {
if (s != null) {
try {
s.close();
} catch (IOException e) {
System.out.println("close:" + e.getMessage());
}
}
}
}
}
and my server file :
public class serverRPC extends Thread {
String request;
String response;
public static void main(String args[]) {
try {
int serverPort = 8888;
ServerSocket listen_socket = new ServerSocket(serverPort);
while (true) {
Socket clientSocket = listen_socket.accept();
Connection c = new Connection(clientSocket);
}
} catch (IOException e) {
System.out.println("Listen socket:" + e.getMessage());
}
public serverRPC(String s) {
request = s;
}
}
class Connection extends Thread {
ObjectInputStream in;
ObjectOutputStream out;
Socket clientSocket;
public Connection(Socket aClientSocket) {
try {
clientSocket = aClientSocket;
in = new ObjectInputStream(clientSocket.getInputStream());
out = new ObjectOutputStream(clientSocket.getOutputStream());
this.start();
} catch (IOException e) {
System.out.println("Connection:" + e.getMessage());
}
}
public void run() {
try {
MathsTutor mt = (MathsTutor) in.readObject();
InetAddress ip = clientSocket.getInetAddress();
System.out.println("The Received Message from Client at address:/" + ip.getHostAddress());
System.out.println("====================================");
MathsTutor mt1 = new MathsTutor();
out.writeObject(mt1);
while(true) {
// Read from input
String command = in.readUTF();
System.out.println(command);
}
//System.out.println();
} catch (EOFException e) {
System.out.println("EOF:" + e.getMessage());
} catch (IOException e) {
System.out.println("readline:" + e.getMessage());
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
} finally {
try {
clientSocket.close();
} catch (IOException e) {/*close failed*/
}
}
}
}
The problem is when I run server and then client on cmd, the client side displays the welcome msg and puts cursor on another line for user input but, I can't type anything, the cursor just blinks... I know this might be simple but it has taken already 3 hours for me and I'm stuck in the same thing.
The cursor marked with red keeps blinking but doesn't let me type anything.
You're writing an object with writeObject() and trying to read it with readUTF(). Illogical.
objects written with writeObject() must be read with readObject().
strings written with writeUTF() must be read with readUTF().
primitives written with writeXXX() must be read with readXXX(), for most values of X.

cannot read all response AT Command

what should i do to read all response from AT Command, i have created one method to send AT Command in class SendAtCommand.java but it always give me some blank result, here is my code:
public String sendCommand(String cmd, CommPortIdentifier portX) throws UnsupportedCommOperationException, IOException, PortInUseException {
String result="kosong";
SerialPort port = null;
try {
port = (SerialPort) portX.open("Wavecom", 5000); // Wait max. 10 sec. to acquire port
} catch (PortInUseException e) {
System.err.println("Port already in use: " + e);
System.exit(0);
}
try {
port.setSerialPortParams(
115200,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
} catch (Exception e) {
System.out.println(e.toString());
}
BufferedReader is = null;
PrintStream os = null;
try {
is = new BufferedReader(new InputStreamReader(port.getInputStream()));
} catch (IOException e) {
System.err.println("Can't open input stream");
is = null;
}
try {
os = new PrintStream(port.getOutputStream(), true);
} catch (IOException e) {
System.err.println("Can't open output stream");
is = null;
}
os.print(cmd);
os.print("\n\r");
String respon;
try {
Thread.sleep(1000);//asal 3000
} catch (InterruptedException ex) {
Logger.getLogger(ThreadConsloe.class.getName()).log(Level.SEVERE, null, ex);
}
try {
while ((respon = is.readLine())!=null) {
result=is.readLine();
try {
Thread.sleep(1500);//asal 3000
} catch (InterruptedException ex) {
Logger.getLogger(ThreadConsloe.class.getName()).log(Level.SEVERE, null, ex);
}
if(result.contains("\n")){
// result.rep
}
System.out.println("result "+result);
}
} catch (IOException e)
{
System.err.println("Can't recieve input signals");
}
port.close();
return result;
}
and i am try to send AT Command using above method like this :
CommPortIdentifier port = CommPortIdentifier.getPortIdentifier("COM15");
SendAtCommand sendX = new SendAtCommand();
String provMenu= sendX.sendCommand("AT+STGI=0", port);
The result (Hyperterminal output) of AT+STGI=0 sholud look like this :
AT+STGI=0
+STGI: "i-SEV Menu"
+STGI: 1,3,"Isi Ulang",0
+STGI: 2,3,"Transfer",0
+STGI: 3,3,"Optional",0
and the result (java output) using my code is :
result
result +STGI: "i-SEV Menu"
result +STGI: 1,3,"Transfer",0
result
result
I assume reason is that you do readLine twice, but print only once. It should be:
while ((result = is.readLine()) != null) {
try {
(reason changed to result variable)

Maximum no. bytes that can be written on com port

I have written a code for serial communication using RXTX comm.When i write 13000 bytes on port then nothing is written but when i write 115200 or less bytes it works like a charm.One more thing this only happens on some systems.
Update:
Below is my code that write bytes on port:
public String portWriter(byte[] messageString) throws NoSuchPortException {
if (Processing.serialPort == null) {
System.out.println("serial port is null");
Processing.portId = CommPortIdentifier.getPortIdentifier(Processing.portText);
try {
Processing.serialPort = (SerialPort) Processing.portId.open("SimpleWriteApp", 2000);
} catch (PortInUseException e) {
return "Port in use by another application.";
}
try {
Processing.serialPort.setSerialPortParams(Processing.speed,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
} catch (UnsupportedCommOperationException e) {
return "Unsupported comm operation.";
}
}
try {
outputStream = Processing.serialPort.getOutputStream();
outputStream.flush();
} catch (IOException e) {
return "Unable to write on port.";
}
try {
//System.out.println("write " + new BigInteger(1, messageString).toString(16));
outputStream.write(messageString);
} catch (IOException e) {
return "Unable to write on port.";
}
return null;
}

Maintain server after socket killing

So I have this simple server. What I want to do is keep the server running and waiting for another client, when I kill the clients socket (telnet -> end process).
private ServerSocket serv;
public Server() throws IOException {
try {
serv = new ServerSocket(port);
serv.setReuseAddress(true);
while(true) {
Socket sock = serv.accept();
try {
BufferedReader netIn = new BufferedReader(new InputStreamReader(sock.getInputStream()));
PrintWriter netOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(sock.getOutputStream())), true);
while(true) {
//do stuff
}
} finally {
sock.close();
}
}
} catch (SocketException e) {
recreateSocket();
} catch (IOException e) {
e.printStackTrace();
}
}
private void recreateSocket() {
try {
ServerSocket socket = ServerSocketFactory.getDefault().createServerSocket(port);
serv = socket;
} catch (IOException e) {
e.printStackTrace();
}
}
Atm it throws bindException, how to deal with it.
Add catch statement(s) to before the finally block (but don't call recreateSocket() there )
Update to clarify, something like this:
while(true) {
//do stuff
}
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
sock.close();
Start a new thread to handle each accepted connection.
The reason is that you are creating a server socket again. You don't need to do this (the previous one is still working which is why you get a bind exception). This is what you want to do:
private ServerSocket serv;
public Server(int port) throws IOException
{
try {
serv = new ServerSocket(port);
serv.setReuseAddress(true);
while(true) {
Socket sock = serv.accept();
try {
BufferedReader netIn = new BufferedReader(new InputStreamReader(sock.getInputStream()));
PrintWriter netOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(sock.getOutputStream())), true);
// do stuff
} catch(SocketException e) {
e.printStackTrace();
} finally {
sock.close();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}

Categories