Is it possible to keep sockets open infinite time - java

I'm new to network programming. I'm interested is it possible to establish network connection via sockets between Java server and C client and keep the connection open infinitely?
I want to keep the connection open to exchange XML data between the clients.

Is is theoretically possible to keep server sockets open an indefinitely long amount of time; however, it is not possible to do so with the client-side socket. The main reason why is because the client side socket is dependent on the server side socket handling the data, and the server socket may close the connection.
While it might be possible to keep a connection open indefinitely, practical aspects typically ensure that such sockets don't stay open forever. Network outages, misconfiguration in intermediate routers, exhaustion of bandwidth, lack of computing power, etc. all collude to ensure that point to point connections are at best temporary.
Note that a server side socket is a socket that receives requests to connect (spawning off connections which have their own return sockets), so it can be open even when there are no connections. If you think of a socket as an open connection to another computer, you will need to reorient your thinking to have server sockets make any sense.

Nothing is infinite (in computing), but you can keep a socket connection open as long as both applications are running.

This is more a plea than an answer, but as a user I've found sockets drop all the time. You can't keep them open indefintely. When a socket closes unexpectedly, please (A) let the user know the connection has been dropped and (B) make it real easy to reestablish the same connection. Okay, this involved games, but I've had clients that wouldn't admit the server was gone and servers that wouldn't recognise I was the same person as the one with the dropped connection.

Related

java help understanding how socket connections work

I am completely new to creating a network connection in java so I apologize if this is a stupid question.
I am trying to create a D&D companion in java that will allow a player to create their character and then send it to the DM so that they can view it and make changes and send it back to the player. I want to be able to make it so that any time a field is changed on one computer it will also be changed on the other computer.
After a bunch of research online I have been able to create a socket connection between the DM(server) and the player(client) and pass a message between the two but I am not sure how a socket connection works after this initial connection is made. My research has not been very clear on this. I have found many resources that have said that java closes the socket after a message has been passed and many that say that the socket stays open.
If java closes the socket then my problem is easy enough to solve because then I will just have to open a new socket every time I need to pass data making sure that I pass the IP address of the client to the server the first time I make a connection.
My real questions come in when a socket stays open.
If the socket stays open and multiple clients connect to the server, will the server just shout over the network whenever it transmits a message so that all clients receive the message? (If this is the case then I know I can just attach a username to the front of the message so that the client can determine if the server is talking to it.)
If the server does not shout then how do I specify which client I want the server to talk to?
Will I have to add a loop to my receive methods so that the client/server is constantly listening for a transmission from the server/client or will java automatically do so after I run the method the first time?
I have found many resources that have said that java closes the socket after a message has been passed
You found them where?
and many that say that the socket stays open.
All those are correct. Java never closes connections. The application closes connections.
If java closes the socket then my problem is easy enough to solve because then I will just have to open a new socket every time I need to pass data making sure that I pass the IP address of the client to the server the first time I make a connection.
It doesn't.
My real questions come in when a socket stays open.
If the socket stays open and multiple clients connect to the server, will the server just shout over the network whenever it transmits a message so that all clients receive the message?
No. It will respond via the socket that is connected to the corresponding client.
(If this is the case then I know I can just attach a username to the front of the message so that the client can determine if the server is talking to it.)
Unnecessary.
If the server does not shout then how do I specify which client I want the server to talk to?
The server responds via the same socket it read the request from.
Will I have to add a loop to my receive methods so that the client/server is constantly listening for a transmission from the server/client
No, you will have to add a thread per accepted socket, that loops reading requests until end of stream.
or will java automatically do so after I run the method the first time?
No.
You seem to have been reading some truly appalling drivel. Take a look at the Custom Networking section of the Java Tutorial.
Adding to EJP's wise answer, it might be worth clarifying:
Sounds like you (wisely) use TCP, so your Socket represents a connection between 1 server and 1 client. No "shouting". In examples such as this , when connection is established (namely, client obtains a Socket by calling "new Socket" and server obtains a Socket by calling "accept"), those Sockets are dedicated to those 2 specific endpoints. So if 10 clients connect to 1 server, the server will keep 10 Sockets and won't mix them up. A bit like a poor secretary that has 10 phones on his desk and answers them all - despite the mess, each earpiece is clearly connected to 1 customer.
The connection can hold for a while & serve several messages. It will terminate when either one of the sides calls 'socket.close', or it can be terminated by underlying 3rd parties (operating system, proxies, firewalls).
For your first version, or for simple business requirements, it's probably enough to converse over this 1 simple connection. However, for commercial critical data that requires 'assurance of delivery', you might need to invest some careful thought & possibly tools such as RabbitMQ.
Good luck:)

handling a lot of sockets in a server efficiently

I have to write a program in which clients send the server some number and wait to its response, other random number. It works Infinitely-send number and wait for response and so on...
I would like to write a server which gets a lot of connections ( and creates sockets) how can I do that in effeicient way (without creating thread to every socket created)?
Is it better to open and close sockets for every request and response?
Is there a way to send answer over a socket when I don't know which one is the right socket, but I know that all the sockets starts from the same client computer and I know the port source of the client
(I thought about making sockets array)
how can I do that in effeicient way (without creating thread to every socket created)?
You are assuming without proof that a new thread per socket is inefficient. It isn't.
Is it better to open and close sockets for every request and response?
No. Take a look at the history of HTTP. The major change between 1.0 and 1.1 was the introduction of persistent connections, which was done regardless of server-side architectures.
Is there a way to send answer over a socket when I don't know which one is the right socket
I don't understand how that situation could possibly arise. The answer only makes sense in the context of a specific session, which is associated with a specific socket. If you aren't retaining that information you should be. It's just a data structure problem.
but I know that all the sockets starts from the same client computer and I know the port source of the client (I thought about making sockets array)
If you can remember the source port you can remember the socket itself. Again, this is just a data structure problem. And there is no need for the assumption/constraint that all connections are from the same client. And unless that client is multi-threaded there is no need for multiple connections from it at all.

Meaning of "java.io.IOException: Connection timed out" after connect phase

Could be related: Difference between Connection timed out and Read timed out
I have written a java server application using nio.
I connected a client to my server application and unplugged the network cable of the client. On the server side, I didn't get any exception immediately but after some time (8 minutes or so), I got a "IOException: Connection timed out"
Here is a partial stack trace:
java.io.IOException: Connection timed out
at sun.nio.ch.FileDispatcherImpl.read0(Native Method)
at sun.nio.ch.SocketDispatcher.read(SocketDispatcher.java:39)
at sun.nio.ch.IOUtil.readIntoNativeBuffer(IOUtil.java:225)
at sun.nio.ch.IOUtil.read(IOUtil.java:198)
at sun.nio.ch.SocketChannelImpl.read(SocketChannelImpl.java:375)
........
Till this time, when I saw the netstat output, I see that the socket state of this particular client connection is shown as ESTABLISHED.
Questions are:
Is this timeout configurable?
Why does the netstat output show the socket state as ESTABLISHED? Ideally it should be CLOSE_WAIT (as the client got disconnected)
No it is not configurable. It is the result of retransmit timeouts. It wouldn't happen at all unless the application kept writing, or had pending writes when the disconnect happened.
It shouldn't be CLOSE_WAIT, as no FIN had been received. Ergo it should be ESTABLISHED.
That timeout is generally not configurable as it depends on the possibilities offered by the operating system. Unix in general does not allow a process to fix the connection timeout and generally it is fixed to around two minutes. Perhaps some versions of linux/BSD systems allow this to be configured, but that's not portable and normally is not allowed to fix it to the user (only the administrator). This has to do with the number of retransmissions and the timeouts used for each try, and is under the exclusive control of the TCP implementation.
When you finish a connection you pass through two states (FIN_WAIT and TIME_WAIT) that are not timeout states. The first of two is to get the other end's response (you can close your side of the connection telling the other side you are not going to send more data, but you have to wait for the other end to do the same thing) The TIME_WAIT is a special state that the kernel maintains for a closed connection to process (and discard) all the possible retransmissions of the last frames that can be in course after the connection is closed. They have nothing to do with timeouts.
A tcp connection has no timeout implicit. Two machines can pass weeks without interchanging any info if they have nothing to transmit. You can control the use of some kind of heartbeat between silenting connections to check their liveness with one socket option (SO_KEEPALIVE) This option makes the tcps at both sides to interchange empty packets to know if the other side is still alive. Again, you can only control the use of this packets, not the frequency or the number of lost frames that closes the connection (this can be configured in linux, but touching the kernel configuration only in administrator mode)
Note 1 (answer to #Krishna Chaitanya P)
If you unplugged the cable and got an exception some time later, it can be one of two reasons for that to happen:
You continued writing to that connection and the sending buffer filled up without being acknowledged in time (this is rare, as normally your process get blocked in write(2) system call when this happens) and some timeout (in the java implementation of socket) did occur.
Your java implementation of tcp socket uses the SO_KEEPALIVE option (the most probable thing). As I said before, you have boolean control to use or not use it, but you cannot adjust the time between keepalives or the number of them that drops your connection. Try to call getKeepAlive()/setKeepAlive(boolean) methods on the Socket class to control this feature. I have not seen in the documentation if the connected socket is, by default, keepalived or not. This is, by far, a commonly used option in a server, as it allows to disconnect the clients that lose connections without telling to the server.
In my experience, the cause for this exception occurring for a connected socket was always due to a firewall closing connections that had been idle for too long. I've seen it happen in cloud evironments (AWS, Rackspace) in particular, but it's not limited to that. Most likely, you have some kind of firewall between the 2 connection peers, which closes idle connections after some time.
The best fix in an ideal world is to change the firewall configuration, provided you or an operations team has access to it. In any case, it's better if you can handle that use case in your code and gracefully terminate the communication with the other peer.
Because the CLOSE_WAIT state is for a FI waiting for its corresponding FIN from the peer and that is not the case here.
This TO is most probably configurable

Netty - Does closing the socket at the client end close the channel at the server

My TCP server is implemented using Netty. My client using vanilla java.net.Socket to connect to this server. I'm using the same socket to send multiple requests to the server. Once done with all the requests the client calls socket.close().
I'm not closing the channel anywhere in my server code. Also, I've set TCP KEEP_ALIVE on my server. Will closing the socket on the client end automatically close the channel on the server or do I've to do something else explicitly and what is the best practice ?
Usually, if an application closes a socket, its remote peer also notices that the closure. Therefore, you don't need to call close() on both side. However, sometimes, due to network problems, you might not get notified when the remote peer closes the connection. To work around this problem, it's a good idea to send some message periodically, and then you will detect the unexpected closure sooner.
Please note SO_KEEP_ALIVE will not help much here because for most operating systems because the default keep alive time is very long.

Java chat - connection just on request

I just programmed a Java Server-Client Chat (with multiple clients) where they log in, chat and log out. The socket is always started and I listen in a loop.
Now I have to program this kind of chat where the connection isn't always open, so the the connection just stars "on request" (when someone sends a message).
How do I do this? Could you give me some keywords which I should google?
If you want to create a Server and Client that does not have a Open Connection (Correct me If I am wrong) you will have to Open and close the connection manually. As these "connections" represent Streams across the network.
Another Option you can consider is maybe using UDP, but this does not close and open a connection on request it only removes the overhead of TCP and it's reliability features.
From the Datagram Lesson on Oracle.com:
Some applications that you write to
communicate over the network will not
require the reliable, point-to-point
channel provided by TCP. Rather, your
applications might benefit from a mode
of communication that delivers
independent packages of information
whose arrival and order of arrival are
not guaranteed.

Categories