The Socket class documentation is here.
In my code atm, I use a constructor that's like this:
Socket m_Socket = new Socket(m_Address, m_Port);
m_Address is an InetAddress and m_Port is an int.
When this line runs, and the socket cannot be made, the app waits 3 seconds or so before throwing an IOException.
I can see there is no constructor that takes both InetAddress, int, and another int for timeout. I need to wait 250ms and not ~3 seconds as it is now. This means that I need to set the timeout on the socket, but I cannot find any method to do this. I know we have the method setSoTimeout(timeout), but it needs to be called on an instance of the Socket class. I can instantiate a new Socket by doing this: m_Socket = new Socket();, but then I'd need to set the InetAddress and port, and the Socket class does not seem to have any methods for doing this (except for the constructor).
How do I set the timeout before it actually tries to set the socket?
You may create an unconnected Socket with the default constructor and then call connect() with timeout.
Socket m_Socket = new Socket();
m_Socket.connect(addr,1000);
try
Socket sock = new Socket();
sock.connect(new InetSocketAddress(m_Address, m_Port), 250);
Related
I need to set time for max connection time in a socket client. But if I do like the following code, does not work, because line one open a connection and is a blocking function and never run line two.
How can I setSoTimeout before open connection?
Socket s = new Socket(server.host, server.port);
s.setSoTimeout(server.time);
Socket socket=new Socket();
socket.connect(new InetSocketAddress(host,port),timeout);
Everyone is aware of socket programming in java. we write a code as below:
ServerSocket serverSocket = new ServerSocket(1234);
Socket server = serverSocket.accept();
We know that we create object of serverSocket and next we write serverSocket.accept(); code to receive client request. we know that serverSocket.accept(); wait until new request comes.
but my question is : what serverSocket.accept(); method does internally? might be is running in while loop ? how server identify that any new request is came to serve ? what is the internal implmentation of serverSocket.accept(); method? Any One has idea about this?
On Linux, the ServerSocket.accept() ultimately (in native code) does an accept syscall (see man 2 accept) which blocks waiting for a suitable incoming connection.
There is no while loop in the Java code or in the native code. I've no idea what happens inside the Linux kernel, but at that point this is no longer a Java question.
The same would probably apply for Java on Windows, and for C# or any other programming language that you cared to consider.
You can find this by your own.
public Socket accept() throws IOException {
if (isClosed())
throw new SocketException("Socket is closed");
if (!isBound())
throw new SocketException("Socket is not bound yet");
Socket s = new Socket((SocketImpl) null);
implAccept(s);
return s;
}
How accept() works?
What does the server.accept() method return when no new socket is formed, i.e., when no new connection is made? Is it possible to go to next line of code while sever.accept() is waiting for a new connection?
If you want to do something while the server is waiting for a connection you can use multiple threads. In a single-threaded application you cannot call a function and continue with your work without waiting it to return: either you are waiting for the server to accept a connection, or you are doing other computations.
A possible alternative to threads is setting the SO_TIMEOUT socket option on the server socket. This makes the call to accept throw an exception if a connection is not received within the timeout, allowing you to go to the next line.
For example:
ServerSocket ss = new ServerSocket(8989);
ss.setSoTimeout(10000); // 10 seconds
Socket clientSocket;
try {
clientSocket = ss.accept();
// process connection from client
} catch (SocketTimeoutException ste) {
// connection was not received,
// do something else
}
Another alternative is using non-blocking IO and the Selector class. Here's an example of a non-blocking socket server written this way.
No. server.accept() is a blocking method and it will wait.
From the javadoc
Listens for a connection to be made to this socket and accepts it. The
method blocks until a connection is made.
What would this statement do:
ServerSocket ss=new ServerSocket(4646);
Please explain in layman terms.
The statement effectively tells the JVM to listen on port specified (4646) for incoming connections. By itself it doesn't mean anything since you will have to take incoming connections to that port and use them to build normal Socket objects that will be then used for ingoing/outgoing data.
You could say that the ServerSocket is the object through which real TCP sockets between clients and the server are created. When you create it, the JVM hooks to the operating system telling it to dispatch connections that arrive on that port to your program.
What you typically do is something like:
public AcceptThread extends Thread {
public void run() {
ServerSocket ss = new ServerSocket(4646);
while (true) {
Socket newConnection = ss.accept();
ClientThread thread = new ClientThread(newConnection);
thread.start();
}
}
}
So that you will accept incoming connections and open a thread for them.
Straight from the ServerSocket Java docs:
Creates a server socket, bound to the specified port.
What's a server socket?
This class implements server sockets. A server socket waits for requests to come in over the network. It performs some operation based on that request, and then possibly returns a result to the requester.
public ServerSocket(int port) throws IOException
documentation:
Creates a server socket, bound to the
specified port. A port of 0 creates a
socket on any free port.
That would bind your ServerSocket to port 4646 on the local machine.
You could then accept sockets on this connection with
// pick up server side of the socket
Socket s = ss.accept();
Now, your client can connect to your server, establishing a socket connection, like this
// pick up client side of the socket, this is in a different program (probably)
Socket connectionToServer = new Socket("myserver",4646);
I have this code:
ServerSocket serverSideSocket = new ServerSocket(1234);
serverSideSocket.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(serverSideSocket.getInputStream()));
And compiler writes me that it cannot find "getInputStream". I do not understand why. In the beginning of my code I do import java.net.*.
Calling of accept returns instance of Socket which has required method getInputStream.
The code might look like this:
ServerSocket serverSideSocket = new ServerSocket(1234);
Socket socket = serverSideSocket.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Great tutorial how to work with sockets in java: http://java.sun.com/docs/books/tutorial/networking/sockets/index.html
This because conceptually a ServerSocket doesn't provide a direct connection object that can be used to send and receive data. A ServerSocket is a tool that you can use with the .accept() method to let it listen on the choosen port and generate a new real connection when a client tries to connect.
That's why you can't get an InputStream from a ServerSocket. Since many clients can connect to the same server, every client will make the server socket generate a new Socket (that is an opened TCP connection) that is returned from .accept() through which you can send and receive using its InputStream and OutputStream.