Trying to get data from RS-232 through sockets
843790Jun 5 2008 — edited Jun 5 2008Hi, I'm trying to get data from RS-232 converter, through sockets but I dont know why in some cases I can get data this is my peace of code. I think that I have to use threads to read the data, if I run I cant get the data but in debug mode in some cases yes.
public class SocketServer implements Runnable {
ServerSocket serverSoc;
double dato;
public SocketServer() {
try {
ServerSocket serverSoc = new ServerSocket(6001);
System.out.println("Servidor corriendo....");
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
/**
* @param args
*/
public static void main(String[] args) {
try {
SocketServer server = new SocketServer();
Thread miHilo = new Thread(server);
miHilo.start();
} catch (Exception e) {
System.out.println("Error en Socket: " + e.getMessage());
}
}
// C�digo para leer el cliente
public void run() {
try {
String fileName = "U:\\PruebaSocket\\Modificado.txt";
File f = new File(fileName);
//Balanza Adventure Ohaus 10.128.16.51
//Mettler Toledo 10.128.16.52
//Instron(1) 10.128.17.16
//Instron(2) 10.128.17.43
InetAddress iaMT = InetAddress.getByName("10.128.16.54");
int puerto = 6001;
System.out.println("Esperando dato: ");
Socket sMT = new Socket(iaMT, puerto);
InputStream isMT = sMT.getInputStream();
//Ciclo infinito
while (true) {
while ((dato = isMT.read()) != -1) {
//ABRIMOS UN BUFFER PARA DESCARGAR LO QUE EL CLIENTE
//NOS ESTA ENVIANDO
InputStream in = sMT.getInputStream();
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
in.read(buf);
//CREAMOS LA INSTANCIA PARA ESCRIBIR EL ARCHIVO
//EN DISCO
FileOutputStream out = new FileOutputStream(new File(
"U:\\PruebaSocket\\Modificado.txt"));
out.write(buf, 0, len);
BufferedReader br = new BufferedReader(new FileReader(
"U:\\PruebaSocket\\Modificado.txt"));
//Data came with letter g, I have to delet it
String datoBalanza = br.readLine().replaceAll("g", "");
datoBalanza = br.readLine().replaceAll("s", "");
//With trim() I eliminate spaces in the String
String data = datoBalanza.trim();
System.out.println("Dato Balanza: " + " IP: "
+ iaMT.toString() + " Dato: " + data);
//Ingreso a la base de datos, la informaci�n
//enviada por los instrumentos
Date fecha = new Date();
SimpleDateFormat sdf = new SimpleDateFormat(
"dd/MM/yyyy hh:mm:ss");
String fechaActual = sdf.format(fecha);
System.out.println(fechaActual);
String leido = "NO";
MapeadorSockets.adicionarDatosPruebas(data, iaMT,
fechaActual, leido, null);
//Aqui, debo buscar tabla(especificaciones_activas)
//el instrumento activo con el retornado en la insercion
//y buscar el limite de control
System.out.println("El dato se adiciono con �xito");
System.out.println(f);
out.close();
f.delete();
f.deleteOnExit();
f.createNewFile();
System.out.println("New File: " + f);
}
//in.close();
//out.close();
}
}
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}