Array of Sockets Java - java

I'm creating server and client java applications. I would like to create an array to store my sockets in. I'm using eclipse, and when I type in this line:
Socket[] sockets = new Socket[3];
Eclipse gives me an error saying "The resource type Socket[] does not implement java.lang.AutoCloseable".
How can I fix this?
Thank you
Try/Catch Statement:
try (
Socket[] sockets = new Socket[3]; //Line giving me error
ServerSocket serverSocket =
new ServerSocket(Integer.parseInt(ip));
Socket clientSocket = serverSocket.accept();
ServerClient client = new ServerClient(clientSocket);
PrintWriter out =
new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
//User input
BufferedReader stdIn =
new BufferedReader(
new InputStreamReader(System.in))
) {
String inputLine;
while ((inputLine = in.readLine()) != null) {
out.println(inputLine);
}
} catch (IOException e) {
System.out.println("Exception caught when trying to listen on port "
+ port + " or listening for a connection");
System.out.println(e.getMessage());
continue;
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

While Socket class itself implements AutoCloseable interface, array of Sockets - does not.
To put it in simple terms: you cannot open or close an array.

The resources defined in a try-with-resources block must all be auto-closeable. That's what it's for. Socket[] is not AutoCloseable, so it cannot be defined there. Move the declaration before the try. Ditto for any other resources you get the error on. Don't treat it as a general declaration block. It isn't.

When I run your code I recevie this error message
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - incompatible types: try-with-resources not applicable to variable type
(java.net.Socket[] cannot be converted to java.lang.AutoCloseable)
I advice you not to use try catch block with resources when you want to define your socket array.
try (
your rest of code
) {
define your array here ---> Socket[] sockets = new Socket[3];
String inputLine;
while ((inputLine = in.readLine()) != null) {
out.println(inputLine);
}
} catch (IOException e) {
your rest of code
Note: Socket class implements Closeable and AutoCloseable , yet array cannot be defined in try block like you tried to do

You can outsmart this problem easily, just create a class containing a socket connection, then build an array of this class object.
Build the class:
Class example
{
Socket con;
The constructor and extra code here
...
}
Then just build the array:
example[] arr=new example[3];

Related

Stream is closed in java

This is the code I have
try
{
reader.read(msg1,0,6);
} catch (SocketTimeoutException e1){
loopcount = 1 ;
reader.close();
writer.close();
client.close();
reader = null;
writer = null;
client = null;
}
try
{
msg2 = new char[2000];
reader.read(msg2,0,intArrLen);
}catch (SocketTimeoutException e1){
loopcount = 1 ;
reader.close();
writer.close();
client.close();
reader = null;
writer = null;
client = null;
}
Inside the method, at this line reader. read (msg1,0,6) able to read the response correctly. After this when trying to read the response at the line reader. read (msg2,0,intArrLen).
It is giving stream is closed exception - Exception: java. I o. IO Exception: Stream closed. So need help in understanding why this exception is coming.
Firstly you are closing the connection of the reader and then without creating a new one calling the function using same reader which is close.
Instead, you can use reader.flush() method .
For more information please refer to the link.

Java .jar gives "The handle is invalid" message but running program in Netbeans does not

Java .jar gives "The handle is invalid" message but running program in Netbeans does not. Any ideas where to begin would be helpful. This programs moves databases from one IP to another.
private String[] readSourceFile() {
//This method returns an array of strings to populate the IP drop down list
ArrayList<String> arr = new ArrayList<>();
String strLine;
try {
FileInputStream fstream = new FileInputStream("SourceIPlist.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
while ((strLine = br.readLine()) != null) {
arr.add(strLine);
}
in.close();
br.close();
fstream.close();
} catch (FileNotFoundException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
} catch (IOException ei) {
JOptionPane.showMessageDialog(null, ei.getMessage());
}
return arr.toArray(new String[arr.size()]);
}
I commented out the in.close(); call and the message stopped. I picked that up from some example I came across. I assumed it closed all the inputs (fstream, br) at once. Now I'm thinking the in.close(); was making an anonymous object or something? Thoughts?
Below are the details for the method.
public void close() throws IOException
Closes this input stream and releases any system resources associated with the stream.
The close method of InputStream does nothing.
Throws:
IOException - if an I/O error occurs.

While readLine() != null loop from BufferedReader created from socket InputStream never exits [duplicate]

This question already has an answer here:
readLine() loop not exiting until remote client closes connection
(1 answer)
Closed 5 years ago.
Im reading the input line by line from a socket InputStream using a BufferedReader but nothing after the while loop seems to get executed. The socket is coming from accept() on ServerSocket not from something like this Socket link = new Socket(address, 80);.
Code
String input;
BufferedReader in = null;
DataOutputStream out = null;
boolean foundConnectionHeader = false;
try {
in = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
out = new DataOutputStream(connectionSocket.getOutputStream());
// Change keep alive connection header to close, add connection header if it doesn't exist
while ((input = in.readLine()) != null) {
if (foundConnectionHeader) {
requestHeaders.add(input);
} else {
if (input.contains("Proxy-Connection: keep-alive")) {
requestHeaders.add("Proxy-Connection: close");
foundConnectionHeader = true;
} else {
requestHeaders.add(input);
}
}
// System.out.println(input);
}
if (!foundConnectionHeader) {
requestHeaders.add("Proxy-Connection: close");
}
System.out.println("DONE");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
It will return null when the peer disconnects.
If you're going to implement HTTP you need a good knowledge of RFC 2616, especially the parts about content length and connection lifetime. Your present code doesn't begin to be adequate.

Java: Socket closing after try-catch blocks

I am attempting a client/server type chat box (using GUI's). I won't get into details of the multi-threading I used in the program since I believe it is not part of the problem (I hope not) and it will be good amount of code to post. Anyways, for both my client and my server I create a socket, and some other stream classes within a try block, and some reason the sockets close after the catch blocks. PS I do NOT call socket.close() method anywhere that could end if early
Server, this is ran into a constructor of one of my class. It breaks down into, my main has the actually server stuff on a different thread, (like my previous post) it is a fix so that the gui can load and run the server stuff without one waiting on the other. Anyways, without all that detail, here is my code
public ChatAppProtocol(Socket sock)
{
super("ChatAppServer");
// this also has a clas var of Socket
this.sock = sock;
try (
PrintWriter output = new PrintWriter(this.sock.getOutputStream(), true);
BufferedReader input = new BufferedReader(new InputStreamReader(this.sock.getInputStream())) ;
)
{
// first stream of a string is the username loging in from client
String name = input.readLine();
// this returns false, so its not closed
System.out.println("closed?: " + this.sock.isClosed());
}
catch (IOException e)
{
e.printStackTrace();
}
// PROBLEM!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// closed after the catch blocks before methods even ends
// p.s. i also plan on using the socket in another method but can't since it closes
System.out.println("closed?: " +this.sock.isClosed());
}
now my client
#FXML
private void login()
{
this.name = this.username.getText().trim();
this.portnum = Integer.parseInt(this.port.getText());
this.name = this.username.getText().trim();
this.ipaddr = this.ip.getText().trim();
try (t
Socket socket = new Socket(this.ipaddr, this.portnum);
PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
)
{
this.sock = socket;
output.println(this.name);
// this returns false, not closed
System.out.println("closed?: " +this.sock.isClosed());
}
catch (UnknownHostException e)
{
System.err.println("Problem at ip: " + this.ipaddr);
System.exit(1);
}
// PROBLEM!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// returns true here, closes before methods end and i cant reuse it
System.out.println("IS IT CLOSED!!!!!! " + this.sock.isClosed());
}
}
so, any reason why both this different class, different files, different project sockets close after try-catch blocks? Can't find answer online, and been on it for a while and I am stuck. I found out about this problem after seeing this on the server side console
java.net.SocketException: Socket is closed
at java.net.Socket.getOutputStream(Socket.java:943)
at chatappserver.ChatAppProtocol.run(ChatAppProtocol.java:62)
Because you're creating socket with the brackets of the try block, it is automatically closed upon exiting the block. Instead, try creating it inside the block itself and it shouldn't be closed:
try {
this.sock = new Socket(this.ipaddr, this.portnum);
PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
output.println(this.name);
} catch (UnknownHostException e) {
System.err.println("Problem at ip: " + this.ipaddr);
System.exit(1);
}
// this.sock should still be open at this point.
Have a read of the Java tutorial on try-with-resources for more information on why you're getting your current behaviour.
You are using try-with-resources, which is roughly an equivalent of:
try
{
this.sock = new Socket(this.ipaddr, this.portnum));
output.println(this.name);
// this returns false, not closed
System.out.println("closed?: " +this.sock.isClosed());
}
catch (UnknownHostException e)
{
System.err.println("Problem at ip: " + this.ipaddr);
System.exit(1);
} finally {
if (this.sock != null)
this.sock.close();
}
Just initialize the socket outside the resources clause of try (...) and it won't get closed

What determines in this code what is sent back to the client? TCP Sockets

In the code below, what determines what will be sent back to the client (the PHP page). I am trying to alter this so that it sends a variable back to the PHP page with an error message that is defined based on actions made in my java code.
Edit: To answer some questions, what I am trying to do is this.
Send a string to the java script with a socket and convert it to a variable to be used in the java script. It will run through some if statements and I need to set the error statements to a variable lets say "reply". I need to send "reply" then back to the PHP file.
public class MyJavaServer {
public static void main(String[] args) {
int port = 20222;
ServerSocket listenSock = null; //the listening server socket
Socket sock = null; //the socket that will actually be used for communication
try {
listenSock = new ServerSocket(port);
while (true) { //we want the server to run till the end of times
sock = listenSock.accept(); //will block until connection recieved
BufferedReader br =
new BufferedReader(new InputStreamReader(sock.getInputStream()));
BufferedWriter bw =
new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
String line = "";
while ((line = br.readLine()) != null) {
bw.write("PHP said: " + line + "\n");
bw.flush();
}
//Closing streams and the current socket (not the listening socket!)
bw.close();
br.close();
sock.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
If I get your question right, the line where the answer gets sent to the peer is
bw.write("PHP said: " + line + "\n");
which writes the given string to bw.

Categories

Resources