This question already has answers here:
Closed 13 years ago.
Duplicate of Implementation of Xmodem Protocol in Java
I've got to implement the xmodem protocol to receive a file from a target device. For that, I have to request the file, then for every 128-byte packet received, I have to send an acknowledgment. My problem is when I open an outputstream to request the file, it will write but after that I can't write again to the outputstream. What is the problem I'm not getting?
package writeToPort;
import java.awt.Toolkit;
import java.io.*;
import java.util.*;
import javax.comm.*;
import javax.swing.JOptionPane;
import constants.Constants;
public class Flashwriter implements Runnable, SerialPortEventListener {
Enumeration portList;
CommPortIdentifier portId;
String messageString = "\r\nFLASH\r\n";
SerialPort serialPort;
OutputStream outputStream,outputStream2;
InputStream inputStream;
//Thread readThread;
String one, two;
String test = "ONLINE";
String[] dispArray = new String[1];
int i = 0;
Thread readThread;
byte[] readBufferArray;
int numBytes;
String response;
FileOutputStream out;
final int FLASH = 1, FILENAME = 2;
int number;
File winFile;
public static void main(String[] args) throws IOException {
Flashwriter sm = new Flashwriter();
sm.FlashWriteMethod();
}
public void FlashWriteMethod() throws IOException {
portList = CommPortIdentifier.getPortIdentifiers();
winFile = new File("D:\\testing\\out.FLS");
while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
if (portId.getName().equals("COM2")) {
// if (portId.getName().equals("/dev/term/a")) {
try {
serialPort = (SerialPort) portId.open("SimpleWriteApp",
1000);
} catch (PortInUseException e) {
}
try {
outputStream = serialPort.getOutputStream();
inputStream = serialPort.getInputStream();
System.out.println(" Input Stream... " + inputStream);
} catch (IOException e) {
System.out.println("IO Exception");
}
try {
serialPort.addEventListener(this);
} catch (TooManyListenersException e) {
System.out.println("Tooo many Listener exception");
}
serialPort.notifyOnDataAvailable(true);
try {
serialPort.setSerialPortParams(9600,
SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
serialPort
.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);
// serialPort.disableReceiveTimeout();
// outputStream.write(messageString.getBytes());
// sendRequest("/r/n26-02-08.FLS/r/n");
number = FLASH;
sendRequest(number);
} catch (UnsupportedCommOperationException e) {
}
}
}
}
}
public void serialEvent(SerialPortEvent event) {
SerialPort port = (SerialPort) event.getSource();
switch (event.getEventType()) {
case SerialPortEvent.DATA_AVAILABLE:
try {
while (inputStream.available() > 0) {
numBytes = inputStream.available();
readBufferArray = new byte[numBytes];
// int readtheBytes = (int) inputStream.skip(2);
int readBytes = inputStream.read(readBufferArray);
one = new String(readBufferArray);
System.out.println("readBytes " + one);
if (one.indexOf("FLASH_") > -1 & !(one.indexOf("FLASH_F") > -1)) {
System.out.println("got message");
response = "FLASH_OK";
// JOptionPane.showMessageDialog(null,
// "ONLINE",
// "Online Dump",
// JOptionPane.INFORMATION_MESSAGE);
// Toolkit.getDefaultToolkit().beep();
// outputStream.write("\r\nONLINEr\n".getBytes());
// outputStream.flush();
// outputStream.write("/r/n26-02-08.FLS/r/n".getBytes());
number = FILENAME;
sendRequest(number);
}
out = new FileOutputStream(winFile, true);
out.write(readBufferArray);
out.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
readBufferArray = null;
// break;
}
// try {
// int c;
// while((c = inputStream.read()) != -1) {
// out.write(c);
// }
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// // readBufferArray=null;
// break;
// }
// if (inputStream != null)
// try {
// inputStream.close();
// if (port != null) port.close();
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
//
//
readThread = new Thread(this);
readThread.start();
}
public void run() {
try {
System.out.println("In run() function ");
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("Interrupted Exception in run() method");
}
}
public void dispPacket(String packet) {
if (response == "FLASH_OK") {
System.out.println("disppacket " + packet);
} else {
System.out.println("No resust");
}
}
public void sendRequest(int num) {
switch (num) {
case FLASH:
try {
// outputStream = serialPort.getOutputStream();
outputStream.write("AT".getBytes());
// outputStream.write("\r\n26-02-08.FLS\r\n".getBytes());
System.out.println("Flash switch");
// outputStream.close();
outputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
break;
case FILENAME:
try {
//outputStream =(serialPort.getOutputStream());
outputStream.write("\r\nSUNSHINE\\06-03-09.FLS\r\n".getBytes());
System.out.println("File name");
outputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
}
Perhaps the streams are blocking.
Java nio has channels that do not block. Try using one of those.
Here's a sample of reading a file with nio. I'm not sure if the same applies for you or not.
I hope it helps.
Related
I am trying to read GPS data from a serial port(ttyACM0) in java using jssc jar which I need to display as a label in a JavaFx application. I have a created a thread for reading the GPS data but this thread is consuming 100% CPU(checked using top command + Shift H) because of which my GUI is getting freezed. This is a sample code I have written for reading GPS data
Serial Interface
import jssc.*;
public class SerInterface {
String portName;
int baud;
boolean lineMode;
// The chosen Port itself
SerialPort port;
public byte[] recvBuff;
public SerInterface(String portName, int baud, boolean lineMode) {
this.portName = portName;
this.baud = baud;
this.lineMode = lineMode;
recvBuff = new byte[8192];
openPort();
if((port == null) || (!port.isOpened()))
System.out.println(portName + " not opened successfully");
}
void openPort() {
port = new SerialPort(portName);
if(port == null)
return;
try {
port.openPort();
} catch (SerialPortException e) {
e.printStackTrace();
}
try {
if(port.isOpened())
port.setParams(SerialPort.BAUDRATE_9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
else
return;
} catch (SerialPortException e) {
e.printStackTrace();
}
System.out.println(portName + " opened successfully");
}
public int recvData() {
int len = 0;
if(port.isOpened()) {
try {
byte[] buff = port.readBytes();
if((buff == null) || (buff.length == 0))
return 0;
len = buff.length;
if(len > recvBuff.length)
len = recvBuff.length;
System.arraycopy(buff, 0, recvBuff, 0, len);
buff = null;
} catch (SerialPortException e) {
e.printStackTrace();
}
}
return len;
}
public void sendData(byte[] sendBuff, int len) {
if(port.isOpened()) {
try {
port.writeBytes(sendBuff);
} catch (SerialPortException e) {
e.printStackTrace();
}
}
}
public boolean validatePort() {
if(!port.isOpened()) {
openPort();
if(port.isOpened())
return true;
else
return false;
}
else
return true;
}
public void flushPort() {
if(port.isOpened()) {
try {
port.purgePort(SerialPort.PURGE_RXCLEAR | SerialPort.PURGE_TXCLEAR);
} catch (SerialPortException e) {
e.printStackTrace();
}
}
}
public void closePort() {
if(port.isOpened()) {
try {
port.closePort();
System.out.println("port closed");
} catch (SerialPortException e) {
e.printStackTrace();
}
}
}
}
GPSReceiver thread extends SerInterface and implements Runnable
#Override
public void run() {
flushPort();
while(true) {
if(!validatePort()) {
try {
sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
continue;
}
int dataLength = recvData();
if(dataLength < 2)
continue;
try {
InputStream gpsStream = new ByteArrayInputStream(recvBuff, 0, dataLength);
BufferedReader br = new BufferedReader(new InputStreamReader(gpsStream, StandardCharsets.US_ASCII));
while(true) {
try {
if (!((output = br.readLine()) != null)) break;
} catch (IOException e) {
e.printStackTrace();
}
extractData();
}
}
catch(NullPointerException e) {
e.printStackTrace();
}
}
Main Thread
GPSInterface objGPSThreadInterface = new GPSInterface(GPSPortName, 9600, true);
GPSThreadInt = new Thread(objGPSThreadInterface, "GPSINT");
I am using jdk-13.0.1 and jssc-2.9.1 jar
i couldn't find any article upon "place call using java with a HSDPA Dongle" on google. i have done port initialization but don't know what to do for placing call.
1) i am using Huawei Dongle.
2) I have found error "NO CARRIER".
3) i am using the following code to detect port or modem and trying to place call but its giving me "NO CARRIER" error ! what mistake i am doing here kindly help me please
import java.io.*;
import java.util.*;
import gnu.io.*;
import java.io.*;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import org.apache.log4j.chainsaw.Main;
import sun.audio.*;
public class GSMConnect implements SerialPortEventListener,
CommPortOwnershipListener {
private static String comPort = "COM6"; // This COM Port must be connect with GSM Modem or your mobile phone
private String messageString = "";
private CommPortIdentifier portId = null;
private Enumeration portList;
private InputStream inputStream = null;
private OutputStream outputStream = null;
private SerialPort serialPort;
String readBufferTrial = "";
/** Creates a new instance of GSMConnect */
public GSMConnect(String comm) {
this.comPort = comm;
}
public boolean init() {
portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
if (portId.getName().equals(comPort)) {
System.out.println("Got PortName");
return true;
}
}
}
return false;
}
public void checkStatus() {
send("AT+CREG?\r\n");
}
public void dial(String phoneNumber) {
try {
//dial to this phone number
messageString = "ATD" + phoneNumber + ";\r\n";
outputStream.write(messageString.getBytes());
System.out.println("Called ");
} catch (IOException e) {
e.printStackTrace();
}
}
public void send(String cmd) {
try {
outputStream.write(cmd.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
public void sendMessage(String phoneNumber, String message) {
char quotes ='"';
send("AT+CMGS="+quotes + phoneNumber +quotes+ "\r\n");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// send("AT+CMGS=\""+ phoneNumber +"\"\r\n");
send(message + '\032');
System.out.println("Message Sent");
}
public void hangup() {
send("ATH\r\n");
}
public void welcomeMessage(){
// open the sound file as a Java input stream
String gongFile = "C:\\Users\\SACHIN\\Desktop\\7001110.mp3";
InputStream in;
try {
in = new FileInputStream(gongFile);
// create an audiostream from the inputstream
// AudioStream audioStream = new AudioStream(in);
// play the audio clip with the audioplayer class
// AudioPlayer.player.start(audioStream);
Clip clip = AudioSystem.getClip();
AudioInputStream inputStream = AudioSystem.getAudioInputStream(
Main.class.getResourceAsStream(gongFile));
clip.open(inputStream);
clip.start();
} catch (IOException | UnsupportedAudioFileException | LineUnavailableException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void connect() throws NullPointerException {
if (portId != null) {
try {
portId.addPortOwnershipListener(this);
serialPort = (SerialPort) portId.open("MobileGateWay", 2000);
serialPort.setSerialPortParams(115200,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
} catch (PortInUseException | UnsupportedCommOperationException e) {
e.printStackTrace();
}
try {
inputStream = serialPort.getInputStream();
outputStream = serialPort.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
try {
/** These are the events we want to know about*/
serialPort.addEventListener(this);
serialPort.notifyOnDataAvailable(true);
serialPort.notifyOnRingIndicator(true);
} catch (TooManyListenersException e) {
e.printStackTrace();
}
//Register to home network of sim card
send("ATZ\r\n");
} else {
throw new NullPointerException("COM Port not found!!");
}
}
public void serialEvent(SerialPortEvent serialPortEvent) {
switch (serialPortEvent.getEventType()) {
case SerialPortEvent.BI:
case SerialPortEvent.OE:
case SerialPortEvent.FE:
case SerialPortEvent.PE:
case SerialPortEvent.CD:
case SerialPortEvent.CTS:
case SerialPortEvent.DSR:
case SerialPortEvent.RI:
System.out.println("Ringing");
/*try {
Thread.sleep(5000);
send("ATA");
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}*/
break;
case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
case SerialPortEvent.DATA_AVAILABLE:
byte[] readBuffer = new byte[2048];
try {
while (inputStream.available() > 0)
{
int numBytes = inputStream.read(readBuffer);
System.out.print(numBytes);
if((readBuffer.toString()).contains("RING")){
System.out.println("Enter Inside if RING Loop");
welcomeMessage();
}
}
//readBufferTrial=readBufferTria;//+new String(readBuffer)+new Date();
//print response message
System.out.print(new String(readBuffer));
} catch (IOException e) {
}
break;
}
}
public void outCommand(){
System.out.print(readBufferTrial);
}
public void ownershipChange(int type) {
switch (type) {
case CommPortOwnershipListener.PORT_UNOWNED:
System.out.println(portId.getName() + ": PORT_UNOWNED");
break;
case CommPortOwnershipListener.PORT_OWNED:
System.out.println(portId.getName() + ": PORT_OWNED");
break;
case CommPortOwnershipListener.PORT_OWNERSHIP_REQUESTED:
System.out.println(portId.getName() + ": PORT_INUSED");
break;
}
}
public void closePort(){
serialPort.close();
}
public static void main(String args[]) {
GSMConnect gsm = new GSMConnect(comPort);
if (gsm.init()) {
try {
System.out.println("Initialization Success");
gsm.connect();
Thread.sleep(5000);
gsm.checkStatus();
Thread.sleep(5000);
System.out.println("Before Auto Answer");
gsm.send("ATS0=1");
Thread.sleep(1000);
gsm.dial("87SSSXXX9105");
// Thread.sleep(1000);
// gsm.welcomeMessage();
// Thread.sleep(1000);
// gsm.welcomeMessage();// for turning on Echo ATE1&W
Thread.sleep(20000);
gsm.hangup();
Thread.sleep(1000);
gsm.closePort();
gsm.outCommand();
System.exit(1);
} catch (Exception e) {
e.printStackTrace();
}
} else {
System.out.println("Can't init this card");
}
}
}
First you have to check if your HSDPA dongle really supports calls. A lot of HSDPA sticks only support SMS and data.
If it does and you have e.g. a virtual serial port you can connect from your Java program to it using e.g. Java RXTX and send AT-Commands like ATDT01234567 (dial 01234567) to the stick.
This is the code which is not running in windows but running in mac
`
public ReadWithoutTimings() {
super();
num = 1;
try {
serialPort = (SerialPort) SearchPorts3P4P.selectedPortIdentifier.open("Read JSE3P4P", 2000);
// serialPort = (SerialPort) portId.open("Read1", 2000);
} catch (PortInUseException e) {
System.out.println(e);
JOptionPane.showMessageDialog(null, e);
}
try {
serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
} catch (UnsupportedCommOperationException e1) {
System.out.println(e1);
}
try {
in = serialPort.getInputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
(new Thread(new SerialReader(in))).start();
}
public class SerialReader implements Runnable {
public SerialReader(InputStream in) {
inputStream = in;
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
br = new BufferedReader(new InputStreamReader(inputStream));
try {
bw = new BufferedWriter(new FileWriter(FILENAME));
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
String inputLine = null;
try {
long start = System.currentTimeMillis();
long end = start + 120 * 1000;// 60 seconds * 1000 ms/sec
while (System.currentTimeMillis() < end) {
if (in.available() > 0) {
while ((inputLine = br.readLine()) != null) {
// series.put(num, inputLine);
// num++;
bw.write(inputLine);
bw.newLine();
bw.flush();
System.out.println(inputLine);
if (inputLine.trim().startsWith("DATE") | inputLine.trim().startsWith("REMARK")
| inputLine.trim().startsWith("TESTED BY")) {
serialPort.close();
inputStream.close();
br.close();
bw.close();
break;
}
}
end = System.currentTimeMillis();
} else if (System.currentTimeMillis() >= end) {
serialPort.close();
inputStream.close();
br.close();
bw.close();
PreviewJse3P4P.search.dispose();
JOptionPane.showMessageDialog(null, "Please reconnect again");
PreviewJse3P4P.frame.setVisible(true);
}
}
new CompareClass();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
public static void main(String[] args) {
/*
* portList = CommPortIdentifier.getPortIdentifiers(); //
* System.out.println(System.getProperty("java.library.path")); while
* (portList.hasMoreElements()) { portId = (CommPortIdentifier)
* portList.nextElement(); if (portId.getPortType() ==
* CommPortIdentifier.PORT_SERIAL) { if
* (portId.getName().equals("/dev/cu.usbserial-FTCC026H")) { //
* System.out.println("Connecting.....");
*
* new ReadWithoutTimings(); } } }
*/
}
}
`This is the code which is running in windows and mac
public static void main(String[] args) {
portList = CommPortIdentifier.getPortIdentifiers();
//System.out.println(System.getProperty("java.library.path"));
while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
if (portId.getName().equals("/dev/cu.usbserial-FTCC026H")) {
System.out.println("Connecting.....");
// if (portId.getName().equals("/dev/term/a")) {
Read reader = new Read();
}
}
}
}
public Read() {
try {
serialPort = (SerialPort) portId.open("Read", 2000);
} catch (PortInUseException e) {System.out.println(e);}
try {
inputStream = serialPort.getInputStream();
} catch (IOException e) {System.out.println(e);}
try {
serialPort.addEventListener(this);
} catch (TooManyListenersException e) {System.out.println(e);}
serialPort.notifyOnDataAvailable(true);
try {
serialPort.setSerialPortParams(9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
////////////////////////////////////put these lines to read line
try {
inputStream = serialPort.getInputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
br = new BufferedReader(new InputStreamReader(inputStream));
////////////////////////////////////////////////////////////////////
} catch (UnsupportedCommOperationException e) {System.out.println(e);}
readThread = new Thread(this);
readThread.start();
}
public void run() {
try {
Thread.sleep(20000);
} catch (InterruptedException e) {System.out.println(e);}
}
public void serialEvent(SerialPortEvent event) {
switch(event.getEventType()) {
case SerialPortEvent.BI:
case SerialPortEvent.OE:
case SerialPortEvent.FE:
case SerialPortEvent.PE:
case SerialPortEvent.CD:
case SerialPortEvent.CTS:
case SerialPortEvent.DSR:
case SerialPortEvent.RI:
case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
break;
case SerialPortEvent.DATA_AVAILABLE:
byte[] readBuffer = new byte[1024];
String num = "";String temp = "";
try {
//put these lines to read line
String inputLine=br.readLine();
System.out.println(inputLine);
//////////////////////////////
} catch (IOException e) {System.out.println(e);}
break;
}
}
}
I made a program that select port from the combo box and press connect button and than send data. It's perfectly working on Mac but not working on window. I have put Rxtx.jar and rxtxSerial.dll to respective folder n jre but still it's not working. May be dll and jar file is not proper. Anybody is having dll & jar file for serial port communication for window. What is the problem not working with window. Even it's showing serial com port it means Rxtx.jar is working ,problem is with dll. Please tell me the reason and how to rectify.
I would be really grateful if someone could point me in the right direction
How would i go about triggering an event that is called when no data is received from the serial communication example below?
Thank you,
Maria.
public void connect(String portName) throws Exception {
CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
if (portIdentifier.isCurrentlyOwned()) {
System.out.println("Error: Port is currently in use");
} else {
CommPort commPort = portIdentifier.open(this.getClass().getName(),
2000);
if (commPort instanceof SerialPort) {
SerialPort serialPort = (SerialPort) commPort;
serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8,
SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
InputStream in = serialPort.getInputStream();
OutputStream out = serialPort.getOutputStream();
theSerialWriter = new SerialWriter(this, out);
new Thread(theSerialWriter).start();
serialPort.addEventListener(new SerialReader(this, in));
serialPort.notifyOnDataAvailable(true);
} else {
System.out.println("Error: Only serial ports are handled by this example.");
}
}
}
public void serialEvent(SerialPortEvent arg0) {
int data;
// boolean setFlagDoorLock = false ;
// if(arg0= 1){}
try {
int len = 0;
while ((data = in.read()) > -1) {
if (data == '\n') {
break;
}
buffer[len++] = (byte) data;
asHexStr = DatatypeConverter.printHexBinary(buffer);
if (asHexStr.contains("FB1")) {
// Thread.sleep(1000);
ActivateSystem = true;
if ((asHexStr.contains("FB1") && (ActivateSystem == true))) {
ActivateSystem = false;
asHexStr = "";
} else {
System.out.println("Here2");
}
}
}
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
System.out.println("Received");
}
}
public static class SerialWriter implements Runnable {
OutputStream out;
SerialPortConnector main = null;
public SerialWriter(SerialPortConnector twoWaySerialComm,
OutputStream out) {
main = twoWaySerialComm;
this.out = out;
}
public void send(String stringToSend) {
try {
int intToSend = Integer.parseInt(stringToSend);
this.out.write(intToSend);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void run() {
try {
int c = 0;
Thread.sleep(1000);
if (asHexStr == "") {
System.out.println("Here");
// ActivateSystem = false;
}
}
// catch ( IOException e )
catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
}
}
public static void main(String[] args) {
try {
(new SerialPortConnector()).connect("COM12");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
You have stated this in a comment:
I need to be able to detect that the id has stopped and after a
timeout(or after it not detecting the id a few times in a row) then
send a url call( i already have a class to send the call)-this should
only be sent once.while it is reading the id however another url call
should be sent again-once only
If I understand this right then you need to check for two different things:
The device stops at sending the ID.
The device sends a number of empty ID's.
This requirement is a kind of tricky. As I've said if no data arrives to the serial port then no serial port event will be fired. I think you can use a Timer to check the timeout and use a counter to register the number of empty ID's arrived. Something like this:
int numberOfEmptyIds = 0;
int maxNumberOfAttempts = 5;
boolean urlSent = false;
long timeoutInMillis = 10000; // let's say 10000 millis, equivalent to 10 seconds
Timer timer = null;
public void connect(String portName) throws Exception {
...
scheduleTimer();
}
public void serialEvent(SerialPortEvent evt) {
if(evt.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
try {
while(in.read(buffer) > -1) {
String asHexStr = DatatypeConverter.printHexBinary(buffer);
if(asHexStr.contains("FB1")) {
scheduleTimer();
numberOfEmptyIds = 0;
} else {
numberOfEmtyIds++;
if(numberOfEmptyIds == maxNumberOfAttempts && !urlSent) {
// send the url here
}
}
}
} catch (IOException ex) {
// Log the exception here
}
}
}
private void scheduleTimer() {
if(timer != null) {
timer.cancel();
}
timer = new Timer("Timeout");
TimerTask task = new TimerTask() {
#Override
public void run() {
if(!urlSent) {
// send the url here
}
}
};
timer.schedule(task, timeoutInMillis);
}
I don't know if this is exactly what you need but hope it be helpful.
I'm working on a really simple Java Client / Server system (Just to get my feet wet with sockets). For some reason, I keep getting a "Socket is closed" error... here is my code..
Server File
public class Server {
public static ServerSocket s = null;
public static void main(String[] args) {
//Create the server socket
int port = 1111;
if (args.length > 0) {
if (isInt(args[0]) && Integer.parseInt(args[0]) < 65537) {
port = Integer.parseInt(args[0]);
}
}
try {
s = new ServerSocket(port);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
s.setSoTimeout(0);
} catch (SocketException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Runnable r = new Runnable() {
public void run() {
while (true) {
Socket caught = null;
try {
caught = Server.s.accept();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (caught == null) {
return;
}
InputStream is = null;
try {
is = caught.getInputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader br = new BufferedReader(new InputStreamReader(is));
try {
String output;
while ((output = br.readLine()) != null) {
handleCommand(output, caught);
}
} catch (Exception e) {
}
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
Thread t = new Thread(r);
t.start();
}
public static boolean isInt(String in) {
try {
Integer.parseInt(in);
return true;
} catch (Exception e) {
return false;
}
}
public static void handleCommand(String in, Socket s1) {
if (in.equalsIgnoreCase("test")) {
System.out.println("Recieved Test Command..");
System.out.println("Sending response..");
PrintStream ps = null;
try {
ps = new PrintStream(s1.getOutputStream(), true);
} catch (Exception e) {
e.printStackTrace();
}
ps.close();
}
}
}
Client File
public class Client {
public static Socket s = null;
public static void main(String[] args) {
int port = 1111;
String server = "localhost";
if (args.length > 0) {
if (isInt(args[0]) && Integer.parseInt(args[0]) < 65537) {
port = Integer.parseInt(args[0]);
}
}
if (args.length > 1) {
server = args[1];
}
try {
s = new Socket(server, port);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (s != null) {
Runnable r = new Runnable() {
public void run() {
while (true) {
InputStream is = null;
try {
is = s.getInputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader br = new BufferedReader(new InputStreamReader(is));
try {
String output;
while ((output = br.readLine()) != null) {
System.out.println(output);
}
} catch (Exception e) {
}
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
Thread t = new Thread(r);
t.start();
PrintStream ps = null;
try {
ps = new PrintStream(s.getOutputStream(), true);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Sending Test message..");
try {
ps.println("test");
} catch (Exception e) {
System.out.println("Error: - " + e.getMessage());
}
}
}
public static boolean isInt(String in) {
try {
Integer.parseInt(in);
return true;
} catch (Exception e) {
return false;
}
}
}
I get the error in the client on line 41 and then a NullPointerException on line 46..
Thanks in advance for any help. I'm just trying to learn here.
in the server on line 61, when you do your first read, your client didn't had the oportunity to send data, so it don't stops in the loop and move forward to close the reader on line 68.
Try to create a class to handle incoming connections at the server, that makes easier to think about what to do in the server, something like ClientHandler would be a good choice ;)
have fun !