I was using the below code for Socket connection in Java and it is giving an error that Socket data type doesn't exist even after importing java.net.*; But when I declare the Socket variable con, above the try block it says that boolean variable and Socket variable don't match. The coding is as follows. Please advise.
import java.net.*;
import java.io.*
public class DTServer {
public static void main (String argv[]) {
int dayTimePort = 13;
try {
ServerSocket dtserver = new ServerSocket (dayTimePort);
while (Socket con = dtserver.accept ()) {
PrintWriter out = new PrintWriter (con.getOutputStream (), true);
Date now = new Date ();
out.println (now.toString ());
con.close ();
}
} catch (Exception e) {}
}
Yes, this is the problem:
while (Socket con = dtserver.accept ())
The while
statement needs a boolean
condition - and a Socket
isn't a boolean
. (And you can't declare a variable in a while
condition either...)
You probably want:
while (true) {
Socket con = dtserver.accept();
...
}
Of course, if you have some other condition you want to use, put that instead of true
. For example, you might want some way of shutting down the server gracefully.
See more on this question at Stackoverflow