java opening a socket on the client side - java

i can't figure out why my client socket keeps falling in an IOException.
When it falls in the IOException i recreate my socket and so it will work again untill it falls again into the Exception and so on ...
the code should always read out an ip controller from my electrical installation. I cant change anything on the server side. I connect to it and when something happens it post it to the port and i want to be able to read it.
this is the opening socket code
public KnxController(){
try{
System.out.println("Server started");
clientSocket = new Socket(IP, PORT);
outToServer = new DataOutputStream(clientSocket.getOutputStream());
} catch (UnknownHostException e) {
System.out.println("UnknownHostException: kan knx niet vinden");
} catch (IOException e) {
System.out.println("IOException knxcontroller: kan geen data sturen");
}
and here i read out the data
while(true){
try {
DataInputStream din=new DataInputStream(knxC.clientSocket.getInputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(din));
String[] str=br.readLine().split("");
System.out.println(Arrays.toString(str));
} catch (IOException e) {
try {
knxC.clientSocket = new Socket(knxC.IP, knxC.PORT);
} catch (UnknownHostException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} catch(NullPointerException nex){
try {
knxC.clientSocket = new Socket(knxC.IP, knxC.PORT);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
it workes but far from good coding.
any help on how to solve this would be appreciated.

cleaned the above code for anyone who's interested
opening a socket
public KnxController(){
do{
setClientSocket();
try {
outToServer = new DataOutputStream(clientSocket.getOutputStream());
} catch (IOException e) {
log.error("IOException knxcontroller: kan geen data out stream starten naar knx");
} catch (NullPointerException nEx){
log.error("NullPointerException knxcontroller: geen knx host");
}
}while(clientSocket == null);
KnxSocketListener knxL = new KnxSocketListener("KnxSocketListener", this);
knxL.start();
}
public void setClientSocket() {
try {
this.clientSocket = new Socket(IP, PORT);
} catch (UnknownHostException e) {
log.error("UnknownHostException: kan geen socket opbouwen met knx host");
} catch (IOException e) {
log.error("IOException: kan geen socket opbouwen met knx host");
}
}
socketlistener in new thread public class KnxSocketListener
public KnxSocketListener(String name, KnxController knxC) {
threadName = name;
System.out.println("Creating " + threadName );
this.knxC = knxC;
}
public void start () {
System.out.println("Starting " + threadName );
if (t == null) {
t = new Thread (this, threadName);
t.start ();
}
}
public void run()
{
while(true){
try {
DataInputStream din = new DataInputStream(knxC.getClientSocket().getInputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(din));
String[] str=br.readLine().split("");
System.out.println(Arrays.toString(str));
} catch (IOException e) {
knxC.setClientSocket();
} catch(NullPointerException nex){
knxC.setClientSocket();
}
}
}

Related

Serial port communications equipment file is working on Mac but not working on window

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.

Java Send custom object via socket Client, Server, LAN

I want to send object (custom class) via socket from Client to Server. This is my code:
Server:
private class SocketServerThread extends Thread {
#Override
public void run() {
try {
serverSocket = new ServerSocket(socketServerPORT);
while (true) {
clientSocket = serverSocket.accept();
ObjectInputStream inObject = new ObjectInputStream(
clientSocket.getInputStream());
try {
Te xxx = (Te) inObject.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
//DataInputStream dataInputStream = new DataInputStream(
//clientSocket.getInputStream());
//messageFromClient=dataInputStream.readUTF();
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
//activity.msgFromC.setText(messageFromClient);
}
});
}
}
Client:
public Client(String aIPaddres, int aPort, Te u) {
AddressIP = aIPaddres;
Port = aPort;
sendUser = u;
}
protected Void doInBackground(Void... arg0) {
Socket clientSocket = null;
try {
clientSocket = new Socket(AddressIP, Port);
ObjectOutputStream outObject = new ObjectOutputStream(
clientSocket.getOutputStream());
outObject.writeObject(sendUser);
//DataOutputStream daneWyjsciowe = new DataOutputStream(
//clientSocket.getOutputStream());
//daneWyjsciowe.writeUTF("Czesc!" );
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//response = "UnknownHostException: " + e.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//response = "IOException: " + e.toString();
} finally {
if (clientSocket != null) {
try {
clientSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
Custom class (Te.class):
public class Te implements Serializable {
public String message;
public Te(String m){
message=m;
}
}
When I passing simple data i.e. String there is no problem. But now I want to pass object, but there is always ClassNotFoundException at server. I read lot of stacks but I didnt find answer. Could U help me?

Java network client-server (file sneding), stuck in client receive loop

i tried to make a simple client-server (with some gui) the server sends the data and the client receive it (the save of the file works too) but the client seems to be stucked in the receive-loop.
I started both threads with ".start()".
I have marked the position of the problem with bold style.
My some of you have a idea why the programm in the client dont goes on... - best wishes ghali
Server:
public class Server extends Thread implements Runnable{
public File choosenfile;
public int port = 42001;
public boolean running = true;
public String myAdress = "localhost";
public ServerSocket serverSocket;
public BufferedInputStream bis;
public boolean debug = true;
public OutputStream os;
public void run() {
try {
serverSocket = new ServerSocket(port);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while(running){
Socket socket = null;
try {
System.out.println("Listening on port: "+port);
socket = serverSocket.accept();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*
* Dies ist die stelle an der man einen Thread aufmachen kann
*/
// 1. File-Hülle anlegen dazu muss man deren größere wissen
if(debug) System.out.println("Server: 1.");
int count;
byte[] buffer = new byte[1024];
try {
os = socket.getOutputStream();
} catch (IOException e1) {
e1.printStackTrace();
}
BufferedInputStream in = null;
try {
in = new BufferedInputStream(new FileInputStream(choosenfile));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
try {
while ((count = in.read(buffer)) > 0) {
os.write(buffer, 0, count);
os.flush();
}
} catch (IOException e1) {
e1.printStackTrace();
}
if(debug) System.out.println("Server: finish sending");
try {
os.flush();
if(debug) System.out.println("Server: close");
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
running =false;
}
}
}
Client:
public class Client extends Thread implements Runnable{
public Gui gui; //graphical surface
public boolean running = true;
public boolean debug =true;
//Networkstuff
Socket socket;
DataInputStream is;
public byte[] returnFile;
public Client(Gui gui){
this.gui = gui;
}
public void run() {
try {
socket = new Socket(InetAddress.getByName(gui.inetAdress),gui.portServer);
} catch (UnknownHostException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream(gui.path);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
BufferedOutputStream out = new BufferedOutputStream(fos);
byte[] buffer = new byte[1024];
int count;
InputStream in = null;
try {
in = socket.getInputStream();
int i =0;
}
catch (IOException e1) {
e1.printStackTrace();
}
try {
while((count=in.read(buffer)) >0){
fos.write(buffer, 0, count);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
**//folloing functions are not executed anymore and i dont know why**
gui.loadPicture();
try {
fos.close();
socket.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
It's quite simple. read() blocks until
data is available in the stream, or
the stream is closed
The server sends bytes to the stream, but never closes it, so the client reading from this stream doesn't have any way to know if some more data will come or not, so it blocks.
Close the stream at server-side, or design a protocol allowing the client to know when to stop reading (like for example sending the number of bytes in the file, then sending these bytes).

Program does not load data correctly while working with ObjectInputStream,ObjectOutputStream

What am I trying to do
Simulate a socialnetwork program,in which you can add your profile,change your status,your picture,add friends etc.The program must save it's content before closing in a file.
How do I intend to do it
As I can not append with ObjectOutputStream. I though of creating an ArrayList<SocialProfiles> (SocialProfiles) in this case are the profiles which I am trying to save.
I want to load the profiles from the file to the ArrayList when the program starts,and when I am done adding profiles, I want to write the profiles from the ArrayList back to the file.
I am using the size of the array as an index.Example when it first writes to the array,it writes to index 0.When it has 1 element it writes to index 1 etc etc.
What is not going as it is supposed to?
The program does not load the data from the file to the array.
What do I call at Main
try {
fileoutput = new FileOutputStream("database.dat");
} catch (FileNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
output = new ObjectOutputStream(fileoutput);
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
fileinput = new FileInputStream("database.dat");
} catch (FileNotFoundException e2) {
// TODO Auto-generated catch block
System.out.println("File database.dat nuk ekziston");
}
try {
input = new ObjectInputStream(fileinput);
} catch (IOException e2) {
}
loadData();
frame.addWindowListener(new WindowAdapter()
{
#Override
public void windowClosing(WindowEvent e)
{
new Thread()
{
#Override
public void run()
{
writeData();
try {
fileinput.close();
fileoutput.close();
input.close();
output.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.exit(0);
}
}.start();
}
});
Methods
public void loadData(){
try{
while (true)
{
SocialProfile temp;
temp = (SocialProfile)input.readObject();
profiles.add(profiles.size(),temp);
}
}
catch(NullPointerException e){
}
catch(EOFException e){
System.out.println("U arrit fund-i i file");
} catch (ClassNotFoundException e) {
System.out.println("Objekt-i i lexuar nuk u konvertua dot ne klasen e caktuar");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void writeData(){
SocialProfile temp;
for(int i=0;i<profiles.size();i++){
temp=profiles.get(i);
try {
output.writeObject(temp);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Try to serialize/deserialize whole array instead of each object.
public void serializeData(String filename, ArrayList<SocialProfile>arrayList) {
FileOutputStream fos;
try {
fos = openFileOutput(filename, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(arrayList);
oos.flush();
oos.close();
} catch (FileNotFoundException e) {
...
}catch(IOException e){
...
}
}
private ArrayList<SocialProfile> deserializeData(String filename){
try{
FileInputStream fis = openFileInput(filename);
ObjectInputStream ois = new ObjectInputStream(fis);
return (ArrayList<SocialProfile>)ois.readObject();
} catch (FileNotFoundException e) {
...
}catch(IOException e){
...
}catch(ClassNotFoundException e){
...
}
}

Java Client Server "Socket is closed"

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 !

Categories