Sockets let's send raw streams of bytes back and forth between both computers, giving you fairly low-level access to the TCP/IP protocol. See the File I/O amanuensis for sample code to do. In TCP/IP each computer has a name, such as roedy.mindprod.com. However, various TCP/IP programs could is running on that computer. eachSocketGets a assigned a number called a port. The HTTP server would usually be assigned 80. Dbanywhere is usually 8889. This is the can specify which service on the local or remote machine you want to connect with. TheSocketis specified like this:roedy.mindprod.com:8889.
SocketProvides the ability to pass raw byte streams between hosts to access the TCP/IP protocol layer in a lower-level way. This can be achieved in a manner similar to accessing file I/O (in Unix, system resources are accessed as files, including network resources). The TCP/IP protocol provides that Each host has a name, such as roedy.mindprod.com. However, it is possible to run many TCP/IP programs on the same host. eachSocketA number called a port is assigned to distinguish between different applications or connections. The port of the HTTP application server is typically specified as 80,dbanywhere, which is usually specified as 8889. In this way, we differentiate between the services you request to connect to a remote or local host. ASocketis defined as address: port, for example roedy.mindprod.com:8889
Flush/Refresh
If you write to aSocket, you usually need-to-call flush-to-force the data out onto the net. If you fail to does, you could wait forever for a response because your complete query was never sent. You don't need flush if you're sending a steady stream of data that would push earlier data out onto the net.
If you are to aSocketWriting data, it is often necessary to call the Flush method to send the data to the network. If the operation fails, it is possible that the complete request message has not been sent successfully, resulting in a persistent wait response. If you are using a steady stream of data, you do not need to call the Flush method because the data flow automatically sends the previous data to the network.
Blocking read/Read blocking
If you read from aSocket, you can hang waiting forever if your use a blocking read.Socket. setsotimeout controls the timeout. The read would eventually die when theSocketConnection fails. This would happen when:
* You close theSocketAt the this end.
* The far end sends a disconnect signal.
* TCP cannot get acknowlegement for packets it have sent, even after several retransmissions. These packets could either be data sent byThe application, or keep-alive messages (if keep-alive have been turned on). Don ' t confuse this with the meaningless HTTP keep-alive parameter.
BySocketWhen reading data, using a blocked read operation can cause permanent waiting.SocketThe Setsotimeout method controls the time-out period.SocketIn the case of a failed connection, the operation to read the data will eventually be stopped.
This situation usually occurs in the following situations:
1. Local shutdownSocket,
2. The remote host/terminal sends a disconnected signal,
3.TCP protocol implementation attempts to resend data multiple times still fail to obtain acknowledgement of the sent packet, or to obtain keep-alive information (if the Keep-alive option for the TCP protocol has already been enabled). Also do not confuse the HTTP protocol with the keep-alive parameter. (HTTP keep-alive option refers to the establishment of a valid long connection between the client and the server, avoids duplication of connection consumption, especially to provide static resource access to the site can greatly improve access efficiency)
Timeouts/Timeout
JavaOffersSocket. Setsotimeout to control how long is willing to wait for a read to complete andSocket. Setsolinger to control what long it lingers, (waits to close when there is still unsent data). When you shutdown, the other end should continue to read any buffered data to let the other end close before closing Itsel F. Setsotimeout have no effect on what long you is willing to wait for a write (how long is willing to wait for the OT She end to accept data), just on how long is willing to wait for the other end to produce data.
To add to the misery, Windows partially ignores the timeout. On Connect, the JVM tries to resolve the hostname to ip/port. Windows tries a NetBIOS NS query on UDP Port 137 with a timeout of 1.5 seconds, ignores any ICMP port unreachable packets and repeats this and the more times, adding up to a value of 4.5 seconds. I suggest putting critical hostnames in your the HOSTS file to make sure they is resolved quickly. Another possibility is turning off NETBIOS altogether and running pure TCP/IP on your LAN.
SocketOfJavaImplementing the interface provides the Setsotimeout method setting the time period that you want to wait for the read operation to complete, providing the Setsolinger method to control the shutdown wait period (wait for data that has not been sent, and then close the connection). When a party closes the connection, the other side will still close the connection after the notification in the read to buffer closes the connected data (this sentence does not knowtranslationis accurate, but the actual operation should be this way, it can be understood that when one side closes the connection unilaterally, you should notify the other party that you have closed the connection so that the other person learns and closes the connection. The Setsotimeout option has no effect on the duration of waiting for a write operation ( Waiting for the other party to receive data for the period of time), and waiting for the other party to produce data about the duration. (The Setsotimeout and the other party send response data is not related to when the other party receives data).
What is more depressing is that Windows systems are irresponsible in ignoring timeouts. For a connection.JavaThe virtual machine strives to resolve the domain name to an IP address and port number. While Windows uses UDP port 137 to send domain name resolution queries to the domain name resolution server, the timeout is set to 1.5 seconds. Ignores any ICMP Port unreachable packets and repeats the same request two times in a row (three times altogether). A total of 4.5 seconds is required. It is therefore strongly recommended that the common domain name address and corresponding IP address and port be written in the hosts file to ensure that it can be resolved quickly. The other is to shut down the Windows NetBIOS service completely in the LAN and access the resources completely using TCP/IP.
Disconnet Detection/Probe connection off
Since TCP/IP sends no packets except when there is traffic, withoutSocket. Setkeepalive (True), it has no on noticing a disconnect until you start trying to send (or to a certain extent recei ve) traffic again.JavaHas theSocket. Setkeepalive (True) method to ask TCP/IP to handle heartbeat probing without any data packets or application programming . Unfortunately, you can ' t tell it how frequently to send the heartbeat probes. If The other end does isn't respond in time, you'll get aSocketException on your pending read. Heartbeat packets in both directions let the other end know is still there. A Heartbeat packet is just an ordinary TCP/IP ACK packet without any piggybacking data.
TCP/IP cannot send packets when the network is busy. If not setSocketSetkeepalive is true, we cannot learn that a connection has been closed unless you attempt to send again (or some receive operation).JavaBy settingSocketThe setkeepalive is true in a way that requires the TCP/IP protocol to perform heartbeat detection without the need to send any packets or application-level programming. Unfortunately, however, you cannot be sure how often TCP/IP sends heartbeat heartbeats. If the other party is unable to respond in a timely manner, When you try to perform a read operation, it generatesSocketException. The heartbeat packet allows both sides to know if the other side is connected. Heartbeat packet is just a normal TCP/IP ACK message that does not need to carry any additional data.
When the applications is idling, your applications could periodically send tiny heartbeat messages to each of the other. The receiver could just ignore them. However, they force the TCP/IP protocol to check if the other end is still alive. These is not part of the TCP/IP protocol. You would has to build them into your application protocols. They act as are-you-still-alive? Messages. I have foundJava' s connection continuity testing to being less that 100% reliable. My bullet-proof technique to detect disconnect are to have the server send a application-level heartbeat packet if it has Not sent some packet in the last of seconds. It has to send some message every-seconds, not necessarily a dummy heartbeat packet. The heartbeat packets thus only appear if the server is idling. Otherwise Normal traffic acts as the heartbeat. The Applet detects the lack of traffic on disconnect and automatically restarts the connection. The downside is your applications has to be aware of these heartbeats and they has to fit into whatever other protocol y OU is using, unlike relying on TCP/IP level heartbeats.
Your app can send small heartbeat messages to each other intermittently when the app is idle. Recipients can completely ignore them, but they force the TCP/IP protocol to verify that the other party is alive. This is not part of the TCP/IP protocol communication specification, you need to establish your own heartbeat protocol, such as Send content as ' are-you-still-alive? ' Information that the original author found through testingJavaThe connection continuity is not 100% reliable. His silver bullet technique is to send an app-level heartbeat packet every 30 seconds through the server, if no packets have been received in the last 30 seconds. Servers must send a packet every 30 seconds, You don't have to be a Puppet's heartbeat packet. Heartbeat packets are generated only when the server is idle. Otherwise, ordinary network communication can replace the work of the heartbeat packet. Yes. The applet probe found that the connection was re-established as a result of a disconnected communication. The negative effect is that your app must always focus on these heartbeat states, and if you use other network protocols you also need to implement the corresponding heartbeat protocol, and the different remainder depends on the heartbeat of the TCP/IP layer.
However, it's simpler to use the built-inSocket. Setkeepalive (True) method to ask TCP/IP to handle the heartbeat probing without any data packets or application program Ming. Each end with say just periodically sends a empty data packet with it current sequence, acknowledgement and W Indow numbers.
However, usingSocketThe built-in setkeepalive (true) method to require TCP/IP for heartbeat detection does not use any packets or application-level programming implementations to look much easier. Each terminal simply sends an empty packet containing the current sequence, confirming the information and sliding the window number.
The advantage of application level heartbeats was they let's know the applications at both ends was alive, not just the C Ommunications software.
The advantage of application-level heartbeat is that they enable you to understand whether applications at both ends exist, not just communication software.
Server Side socketing/server-side sockets
For a server to accept connections from the outside world, first it opens a serversocket on a port, and not connected to a NY client in particular.
For a server that receives an external connection, first open a serversocket on a port that is not connected to any client, the code is as follows
ServerSocket serversocket = new ServerSocket (port);
Then it calls accept, which blocks until a call comes in.
SocketClientsocket = Serversocket.accept ();
At the point a new ordinarySocketGets created that's connected to the incoming caller. Usually the server would spin off a thread, or assign a thread from a pool to deal with the newSocketand loop back to do another accept.
When a request is received, a new normalSocket, the server typically initiates a thread or takes a thread out of a thread pool to handle the newly generatedSocket, and then loop through the next request.
You can set the your miniature server even if you don't have a domain name. They can get to you byName:ip:port e.g. 65.110.21.43:2222. Even if your is behind a firewall, you use the external facing IP of the firewall. You must then configure your firewall-let incoming calls through and to direct them to the correct server on the LAN.
Even if you don't own a domain name, you can build your own server. Other people can access your server via IP address and port (e.g. 65.110.21.43:2222) (if this requires you to have your own fixed IP on a WAN, this is generally higher than the cost of owning a domain name, But in the LAN you can try LAN address, if you are in a firewall protected LAN, you can use the external IP firewall. You must configure your firewall so that request packets can pass through and access the correct servers within the LAN.
Flow Control/Flow controls
WithSocket. Setreceivebuffersize () can hint to the underlying OS what much to buffer up incoming data. It is not a obligated to listen. Don ' t confuse this and the buffer on the Bufferedinputstream. The lower level buffer on the rawSocket. Large buffers is not always desirable. Using small buffers can tell the other end is getting behind, and it won ' t send data as quickly. If The data is real time, and the amount of data sent are variable depending on how fast you process it, large buffers mean You can get the behind and never catch up.
UseSocketThe Setreceivebuffersize () method lets you tell the underlying operating system how much of the received data is cached. But it's not entirely up to you to decide. Don't putSocketThe buffer is confused with the Bufferedinputstream buffer. This is the originalSocketThe underlying buffer. An oversized buffer does not always meet the needs well. Using a small buffer can notify the other end of your processing speed is already behind, so the other side will not continue to send data immediately come over (large buffer, the other party sent over the data may not have been read and processed, but there is still a lot of space, So the other side will continue to send data to fill the remaining space, but it is possible to cause a large number of data accumulation in the buffer can not be processed, the ideal state is to use a small cache, processing the current data after receiving, processing the next data. If the data is not real-time, the amount of data sent is dynamically dependent on the speed of processing A large buffer will cause the amount of data you are handling to lag behind the amount of data received and will never catch up.
There is a mysterioous methodSocket. Settcpnodelay (True) to "Disable Nagle ' algorithm". As is typical, there are no explanation what Nagle ' s algorinthm are. My TCP/IP text book makes no mention of it. If you're dealing with near real-time data then you may want to look into disabling Nagle ' s algorithm. That's algorithm attempts to ensure, TCP doesn ' t send lots of undersized IP packets byBuffering-up submitted data and keeping it for typically for a few milliseconds to see if is going to give it some MO Re data that could go into the same packet. I am not sure if flush are sufficient to send a packet on the its immediately.
SocketSettcpnodelay (TRUE) is mysteriously used to close the Nagle algorithm. This settcpnodelay method is not discussed here, as it does not explain the Nagle algorithm. If you're dealing with near-real-time data, you might be looking at how to turn off the Nagle algorithm. The Nagle algorithm can determine if more data needs to be written to the packet by staging the packets that have been submitted for many milliseconds. Ensure that TCP does not send a large number of packets that are too small in length. I'm not sure if the flush method will be able to send a packet sufficiently immediately.
Graceful Shutdown/gracefully Close
If you simply close aSocket, you can lose data of were previously sent but which has not yet been delivered. Chop things off in mid message. So, how do I shut down gracefully? My approach is this. When the client wants to shut down, it sends a close message. The server echos it back and on receipt of the close message, the client closes theSocket. That's the client is guaranteed to being unhooked from waiting on a read, and all are guaranteed the server and client each Recieved the last remaining messages before theSocketwas closed.
If you simply close aSocketConnection, you may lose data that was previously sent but not arrived (delivered). This may result in incomplete data. So, what if the connection is gracefully closed? The author's theory is that when a client tries to close a connection, it first sends a shutdown message. The server returns the closed message content and confirms the shutdown information ( It is possible to increase the acknowledgement of closing information in order to avoid sending time-out packets back to the sender, both of which may be the same, and to close the connection after the client receives the acknowledgement. The client then makes sure that the status of the wait read operation is lifted, and that you want to ensure that the client and server receive the final message before shutting down.
Http://www.cnblogs.com/diyunpeng/archive/2011/07/21/2112380.html
Java Socket Simple Grooming