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
Related
I am making a voice chat program. I have two servers one for voice and one for messages. When I connect two people I get this error, Thank you in advance. I attached the client code, ClientAudio code and the Client receive code
java.io.StreamCorruptedException: invalid type code: 00
at java.io.ObjectInputStream$BlockDataInputStream.readBlockHeader(ObjectInputStream.java:2508)
at java.io.ObjectInputStream$BlockDataInputStream.refill(ObjectInputStream.java:2543)
at java.io.ObjectInputStream$BlockDataInputStream.read(ObjectInputStream.java:2702)
at java.io.ObjectInputStream.read(ObjectInputStream.java:865)
at client.chat$ClientAudioRec.run(chat.java:388)
at java.lang.Thread.run(Thread.java:745)
its calling the error on
try {
bytesRead = ((ObjectInput) i2).read(inSound, 0, inSound.length);
} catch (Exception e) {
e.printStackTrace();
}
Code
public class Client implements Runnable { // CLIENT
private String msg;
public void run() {
try {
s1 = new Socket(ipAddress, port);
s2 = new Socket(ipAddress, 1210);
o1 = new ObjectOutputStream(s1.getOutputStream());
o1.writeObject(name);
serverListModel.addElement(name);
i1 = new ObjectInputStream(s1.getInputStream());
Thread voice = new Thread(new ClientAudio());
voice.start();
while(true) {
msg = (String) i1.readObject();
String[] namePart = msg.split("-");
if(namePart[0].equals("AddName") && !namePart[1].equals(name) && !serverListModel.contains(namePart[1])) {
serverListModel.addElement(namePart[1]);
}
if(namePart[0].equals("RemoveName") && !namePart[1].equals(name)) {
serverListModel.removeElement(namePart[1]);
}
if(!msg.equals(null) && !namePart[0].equals("AddName") && !namePart[0].equals("RemoveName")) {
chatWindow.append(msg+"\n");
}
}
} catch (IOException | ClassNotFoundException e) {
chatWindow.append("Server Closed");
e.printStackTrace();
try {
s1.close();
} catch (IOException e1) {
e1.printStackTrace();
}
mainWindow(true);
}
}
}
public class ClientAudio implements Runnable { // CLIENT AUDIO
public void run() {
try {
o2 = new ObjectOutputStream(s2.getOutputStream());
System.out.println("AUDIO");
int bytesRead = 0;
byte[] soundData = new byte[1];
Thread car = new Thread(new ClientAudioRec());
car.start();
while(true) {
bytesRead = mic.read(soundData, 0, bytesRead);
if(bytesRead >= 0) {
o2.write(soundData, 0, bytesRead);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class ClientAudioRec implements Runnable { // CLIENT AUDIO REC
public void run() {
i2 = new ObjectInputStream(s2.getInputStream());
System.out.println("REC");
SourceDataLine inSpeaker = null;
DataLine.Info info = new DataLine.Info(SourceDataLine.class, af);
try {
inSpeaker = (SourceDataLine)AudioSystem.getLine(info);
inSpeaker.open(af);
} catch (LineUnavailableException e1) {
System.out.println("ERROR 22");
e1.printStackTrace();
}
int bytesRead = 0;
byte[] inSound = new byte[100];
inSpeaker.start();
while(bytesRead != -1)
{
try{
bytesRead = ((ObjectInput) i2).read(inSound, 0, inSound.length);
} catch (Exception e){
e.printStackTrace();
}
if(bytesRead >= 0)
{
inSpeaker.write(inSound, 0, bytesRead);
}
}
}
}
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.
The server accept requests from clients but clients don't get an answer from the server, on the server it accepts client authentication but then the client application shows an error message.
The server and client are on the same LAN.
This is the code of server :
public class UdpServer extends BaseServer {
public static final int UDP_BUFFER = 10 * 1024; // 10Kb
private static final int NUMBER_USER_INFO_REQUEST_RETRIES = 5;
private static final int SECONDS_TO_CHECK_USER_INFO = 15;
DatagramSocket inSocket = null;
DatagramSocket outSocket = null;
BlockingQueue<DatagramPacket> incomingRequests = null;
BlockingQueue<DatagramPacket> outgoingRequests = null;
HandleIncomingPackets handleIncomingPackets = null;
HandleRequests handleRequests = null;
HandleOutgoingPackets handleOutgoingPackets = null;
HandleUserInfoUpdates handleUserInfoUpdates = null;
public UdpServer() throws IOException {
this(4445);
}
public UdpServer(int port) throws IOException {
super();
inSocket = new DatagramSocket(port);
outSocket = new DatagramSocket();
try {
serverUserInfo = new UserInfo(UserInfo.SERVER_USERNAME, inSocket.getLocalAddress().getHostAddress(), inSocket.getLocalPort());
} catch (InvalidDataException e) {
if (DEBUG)
System.out.println("oops... initialising serverUserInfo");
}
incomingRequests = new LinkedBlockingQueue<>();
outgoingRequests = new LinkedBlockingQueue<>();
}
public void run() {
handleIncomingPackets = new HandleIncomingPackets();
handleRequests = new HandleRequests();
handleOutgoingPackets = new HandleOutgoingPackets();
handleUserInfoUpdates = new HandleUserInfoUpdates();
handleIncomingPackets.start();
handleRequests.start();
handleOutgoingPackets.start();
handleUserInfoUpdates.start();
System.out.println("Server Started");
}
private class HandleIncomingPackets extends Thread {
private boolean canRun = true;
private byte[] buf;
private DatagramPacket packet;
#Override
public void run() {
while (canRun) {
buf = new byte[UDP_BUFFER];
packet = new DatagramPacket(buf, buf.length);
try {
inSocket.receive(packet);
} catch (IOException e2) {
if (DEBUG)
System.out.println("ops... receiving a packet from socket");
continue;
}
incomingRequests.add(packet);
}
}
public void stopHandleMessages() {
canRun = false;
}
}
private class HandleOutgoingPackets extends Thread {
private boolean canRun = true;
#Override
public void run() {
while (canRun) {
DatagramPacket dp = null;
try {
dp = outgoingRequests.take();
} catch (InterruptedException e1) { }
if (dp == null)
continue;
try {
outSocket.send(dp);
} catch (IOException e) {
if (DEBUG)
System.out.println("could not send a message: " + dp.toString());
}
}
}
public void stopHandleMessages() {
canRun = false;
}
}
private class HandleRequests extends Thread {
private boolean canRun = true;
#Override
public void run() {
while (canRun) {
DatagramPacket dp = null;
try {
dp = incomingRequests.take();
} catch (InterruptedException e1) { }
if (dp == null)
continue;
String the_msg = new String(dp.getData(), 0, dp.getLength());
the_msg = the_msg.trim();
String message_type = null;
try {
message_type = Procedures.getMessageType(the_msg);
} catch (XmlMessageReprException e) {
if (DEBUG)
System.out.println("Cannot get the message type :( " + e.getMessage());
continue;
}
if (message_type == null) {
if (DEBUG)
System.out.println("message type is null");
continue;
}
if (Procedures.isLoginMessage(message_type)) {
manageLoginRequest(dp);
} else if (Procedures.isRegisterMessage(message_type)) {
manageRegisterRequest(dp);
} else if (Procedures.isLogoutMessage(message_type)) {
manageLogoutRequest(dp);
} else if (Procedures.isUserInfoAnswerMessage(message_type)) {
manageUserInfoAnswer(dp);
}
// do stuff
}
}
public void stopHandleMessages() {
canRun = false;
}
}
private class HandleUserInfoUpdates extends Thread {
boolean canRun = true;
#Override
public void run() {
while (canRun) {
Calendar c = Calendar.getInstance();
Date now = c.getTime();
for (SimpleIMUser simu : registeredUsers) {
// now - last >= Seconds to check
// now >= last + seconds to check
if (!simu.getUser().isOnline())
continue;
c.setTime(simu.last_update);
c.add(Calendar.SECOND, SECONDS_TO_CHECK_USER_INFO * NUMBER_USER_INFO_REQUEST_RETRIES);
if (now.after(c.getTime())) {
simu.getUser().setOffline();
if (DEBUG)
System.out.println("HandlerUserInfoUpdates - set "+ simu.getUser() + " offline...");
continue;
}
c.setTime(simu.last_update);
c.add(Calendar.SECOND, SECONDS_TO_CHECK_USER_INFO);
if (now.after(c.getTime())) {
sendUserInfoRequest(simu);
if (DEBUG)
System.out.println("HandlerUserInfoUpdates - send a userInfoRequest... to: " + simu.getUser());
}
}
try {
Thread.sleep(SECONDS_TO_CHECK_USER_INFO * 1000);
} catch (InterruptedException e) { }
}
}
public void stopHandleMessages() {
canRun = false;
}
}
/*
* various requests/messages managers
*
*/
private void sendUserInfoRequest(SimpleIMUser simu) {
UserInfoRequestMessage uirm = new UserInfoRequestMessage(serverUserInfo);
String uirmXml = null;
try {
uirmXml = uirm.toXML();
} catch (ParserConfigurationException | TransformerException e1) {
//unlikely to be here
}
DatagramPacket p;
try {
p = new DatagramPacket(uirmXml.getBytes(), uirmXml.getBytes().length,
InetAddress.getByName(simu.getUser().getIp()),
simu.getUser().getPort());
} catch (UnknownHostException e) {
/* if there's error... nothing to do */
return;
}
outgoingRequests.add(p);
}
private void manageUserInfoAnswer(DatagramPacket dp) {
String msg = new String(dp.getData(), 0, dp.getLength());
UserInfoAnswerMessage uiam;
try {
uiam = UserInfoAnswerMessage.fromXML(msg);
} catch (XmlMessageReprException e) {
//nothing to do...
return;
}
UserInfo source = uiam.getSource();
SimpleIMUser simu = getTheUserFromRegistered(source);
if (simu == null)
return;
simu.getUser().locationData(source.hasLocationData());
simu.getUser().setAltitude(source.getAltitude());
simu.getUser().setLatitude(source.getLatitude());
simu.getUser().setLongitude(source.getLongitude());
simu.getUser().setIP(source.getIp());
simu.getUser().setPort(source.getPort());
simu.getUser().setOnline();
simu.last_update = Calendar.getInstance().getTime();
}
private void manageLogoutRequest(DatagramPacket dp) {
String request = new String(dp.getData(), 0, dp.getLength());
LogoutMessage lm = null;
try {
lm = LogoutMessage.fromXML(request);
} catch (XmlMessageReprException e) {
return;
}
UserInfo source = lm.getSource();
SimpleIMUser s = getTheUserFromRegistered(source);
if (s == null)
return;
s.getUser().setOffline();
s.last_update = Calendar.getInstance().getTime();
}
private void manageLoginRequest(DatagramPacket packet) {
String request = new String(packet.getData(), 0, packet.getLength());
LoginMessage lm = null;
UserInfo userOfMessage = null;
String password = null;
SimpleIMUser s;
String answer = null;
InetAddress address;
int port;
try {
lm = LoginMessage.fromXML(request);
} catch (XmlMessageReprException e1) {
if (DEBUG)
System.out.println("Login message cannot be serialized :(");
}
userOfMessage = lm.getUser();
password = lm.getPassword();
if (DEBUG)
System.out.println("Login message recieved from \"" + userOfMessage.getUsername() +"\"");
s = getTheUserFromRegistered(userOfMessage);
if (s == null || (s != null && !s.samePassword(password))) {
if (DEBUG)
System.out.println("Sending REFUSE login to \"" + userOfMessage.getUsername() +"\"");
try {
answer = new LoginMessageAnswer(userOfMessage).toXML();
} catch (ParserConfigurationException | TransformerException e) {
if (DEBUG)
System.out.println("ops... should not be here :(");
}
address = packet.getAddress();
port = packet.getPort();
outgoingRequests.add(new DatagramPacket(answer.getBytes(), answer.getBytes().length, address, port));
} else {
if (DEBUG)
System.out.println("Sending ACCEPT login to \"" + userOfMessage.getUsername() +"\"");
address = packet.getAddress();
port = packet.getPort();
s.getUser().locationData(userOfMessage.hasLocationData());
s.getUser().setAltitude(userOfMessage.getAltitude());
s.getUser().setLatitude(userOfMessage.getLatitude());
s.getUser().setLongitude(userOfMessage.getLongitude());
s.getUser().setIP(address.getHostAddress());
s.getUser().setPort(port);
s.getUser().setOnline();
s.last_update = Calendar.getInstance().getTime();
try {
answer = new LoginMessageAnswer(s.getUser(), String.valueOf(s.getUser().hashCode())).toXML();
} catch (ParserConfigurationException | TransformerException e) {
if (DEBUG)
System.out.println("ops... making a loginAnswer message");
}
outgoingRequests.add(new DatagramPacket(answer.getBytes(), answer.getBytes().length, address, port));
ListMessage listMessage = new ListMessage();
fillListMessage(listMessage, s);
try {
answer = listMessage.toXML();
} catch (ParserConfigurationException | TransformerException e) { }
outgoingRequests.add(new DatagramPacket(answer.getBytes(), answer.getBytes().length, address, port));
}
}
private void manageRegisterRequest(DatagramPacket dp) {
String request = new String(dp.getData(), 0, dp.getLength());
RegisterMessage rm = null;
String answer = null;
try {
rm = RegisterMessage.fromXML(request);
} catch (XmlMessageReprException e) {
if (DEBUG)
System.out.println("Register message cannot be serialized :(");
}
if (DEBUG)
System.out.println("Register message recieved from \"" + rm.getUser().getUsername() +"\"");
if (registeredUsers.contains(new SimpleIMUser(rm.getUser(), "DUMMY")) || rm.getUser().equals(serverUserInfo)) {
if (DEBUG)
System.out.println("Sending REFUSE register to \"" + rm.getUser().getUsername() +"\"");
try {
answer = new RegisterMessageAnswer(rm.getUser(), RegisterMessageAnswer.REFUSED).toXML();
} catch (ParserConfigurationException | TransformerException e) {
if (DEBUG)
System.out.println("ops... should not be here :(");
} catch (InvalidDataException e) {
if (DEBUG)
System.out.println("ops... should not be here :(");
}
} else {
if (DEBUG)
System.out.println("Sending ACCEPT register to \"" + rm.getUser().getUsername() +"\"");
rm.getUser().setOffline();
addUserToRegisteredUsers(new SimpleIMUser(rm.getUser(), rm.getPassword()));
try {
answer = new RegisterMessageAnswer(rm.getUser(),RegisterMessageAnswer.ACCEPTED).toXML();
} catch (ParserConfigurationException | TransformerException e) {
if (DEBUG)
System.out.println("ops... should not be here :(");
} catch (InvalidDataException e) {
if (DEBUG)
System.out.println("ops... should not be here :(");
}
}
outgoingRequests.add(new DatagramPacket(answer.getBytes(), answer.getBytes().length, dp.getAddress(), dp.getPort()));
}
#Override
protected void finalize() throws Throwable {
handleUserInfoUpdates.stopHandleMessages();
handleRequests.stopHandleMessages();
handleOutgoingPackets.stopHandleMessages();
handleIncomingPackets.stopHandleMessages();
inSocket.close();
outSocket.close();
super.finalize();
}
}
Anything you could do to help or tell me what I am doing wrong is appreciated.
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 !
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.