Java Network Programming Socket FAQ
I. Common anomalies and handling in the process of network program operation
The 1th exception is java.net.BindException:Address already in Use:jvm_bind.
The exception occurs when the server side makes a new ServerSocket (port is a 0,65536 integer value) operation. The reason for the exception is that one of the ports like Port has been started and is listening. With the Netstat–an command, you can see a port with a listending state. You can solve this problem by looking for a port that is not occupied.
The 2nd exception is Java.net.ConnectException:Connection Refused:connect.
This exception occurs when the client makes a new Socket (IP, port) operation because either the machine with an IP address cannot be found (that is, it does not exist from the current machine to the specified IP route), or the IP exists, but the specified port is not found for listening. This problem occurs, first check whether the client's IP and port is wrong, if correct, ping the server from the client to see if it can ping, if you can ping (service server to the ping ban will need another way), then look at the server to listen to the specified port program to start, This will certainly solve the problem.
The 3rd exception is the Java.net.SocketException:Socket is closed,
This exception can occur on both the client and the server. The exception is due to the active shutdown of the connection (called the Close method of the socket) and read and write to the network connection.
The 4th exception is java.net.SocketException: (Connection reset or connect reset by Peer:socket write error).
This exception can occur on both the client and server side. This exception is caused by two, the first is that if the socket at one end is closed (or if the active shutdown or shutdown due to an unexpected exit), the other end still sends the data, and the first packet that is sent throws the exception (Connect reset by Peer). The other is an exit, but the connection is not closed when it exits, and the other end throws the exception if the data is read from the connection (Connection reset). Simply speaking, it is caused by read and write operations after a disconnected connection.
The 5th exception is Java.net.SocketException:Broken pipe.
This exception can occur on both the client and the server. In the first case of the 4th exception (that is, after you throw the Socketexcepton:connect reset by Peer:socket write error), the exception is thrown if you continue to write the data. The first two exceptions are to make sure that all network connections are turned off before the program exits, and that the next step is to detect the other person's shutdown connection and to close the connection itself after it closes.
Two Issues to be aware of when writing network programs
The 1th problem is to correctly differentiate between long and short connections. The so-called long connection is permanently maintained once it is established. The short connection is in the following scenario, prepares the data-> establishes the connection-> sends the data-> closes the connection. Many programmers have been writing web programs for years, not knowing what a long connection is and what a short connection is.
The 2nd issue is the maintenance of long connections. The so-called maintenance includes two aspects, the first is to detect the other side of the active disconnected (both the call socket Close method), followed by the detection of each other's downtime, abnormal exit and network impassability. This is a robust communication program must have. Detection of each other's active disconnected is very simple, the main side of the active disconnected, the other side if the read operation, then the return value of only 1, once detected that the other disconnected, you should actively shut down the connection (call the socket Close method). and detect each other's downtime, abnormal exit and network is commonly used by the "Heartbeat", that is, the two sides periodically send data to each other, but also received from the other "heartbeat", if the number of consecutive cycles did not receive the other heartbeat, you can judge the other or the outage or abnormal launch or the network is not through, At this point, you also need to actively close your own connection, if the client can be delayed after a certain time to initiate the connection. Although the socket has a keep alive option to maintain the connection, if you use this option, it typically takes two hours to discover each other's downtime, abnormal exit, and network impassability.
The 3rd issue is dealing with the issue of efficiency. Whether it's a client or a server, if it is a long connection a program requires at least two threads, one for receiving data, one for sending heartbeats, writing data without a dedicated thread, and, of course, a class of threads (commonly known as worker threads) for processing messages, which means that the receiving thread is only responsible for receiving data , and then distribute it to the worker for data processing. If it is a short connection, you do not need to send a heartbeat of the thread, if the server also requires a dedicated thread responsible for the connection request of the listener. These are the overall requirements of a communications program, specifically how to design your program, it depends on your own design level. -------------------------------------------------------------Socket Communication (send & receive)Recent work needs to do a little socket communication things, accumulate a little experience, with everyone to share through a short connection to receive the socket return message, dead Loop, respectively, to determine the reception and timeout, to identify the connection between the status of the byte stream to obtain a socket return message, The main reason is that there are anomalies in our system communication through the ReadLine way. The specific client code is as follows:
Import java.net.*;
Import java.io.*; Import Org.apache.log4j.Logger;
public class Socketclient {static Logger log = Logger.getlogger (SocketClient.class.getName ()); Logging Information
Private String HostName;
private int portnum;
private int delaysecond; The dispatch receives the return message delay public socketclient () {
This.hostname = "192.168.0.1";
This.portnum = 7000;
This.delaysecond = 50000;
Pfileop = null;
Private Socket Getsocket () {
Socket socket = NULL;
try {
Socket = new Socket (hostName, portnum);
catch (Unknownhostexception e) {
System.out.println ("--> Unknown host Name:" + hostName + "exception");
catch (IOException e) {
System.out.println ("-hostname=" + hostName + "portnum=")
+ Portnum + "---->io Abnormal Error" + e.getmessage ());
}
return socket;
}
public string SendMessage (string strmessage) {
String str = "";
String serverstring = "";
Socket socket;
try {
Socket = Getsocket ();
Socket.setkeepalive (TRUE);
if (socket = = NULL) {//failed to get the specified socket object, socket communication is NULL
return "0001";
}
PrintWriter out = new PrintWriter (Socket.getoutputstream ());
Log.info ("----> Send a newspaper paper =" +strmessage);
Out.println (strmessage);
Out.flush ();
BufferedReader in = new BufferedReader (New InputStreamReader (
Socket.getinputstream ()));
Long sendtime = System.currenttimemillis ();
Long receivetime = System.currenttimemillis ();
Boolean received = FALSE; Message received successfully
Boolean delaytoolong = false;
serverstring = null;
while (!received &&!delaytoolong) {
if (Socket.getinputstream (). Available () > 0) {
serverstring = In.readline ();
Char tagchar[];
Tagchar = new char[1024];
int Len;
String temp;
String rev = "";
if (len = In.read (Tagchar))!=-1) {
temp = new String (Tagchar, 0, Len);
Rev. + temp;
temp = null;
}
serverstring = rev;
}
Receivetime = System.currenttimemillis ();
if (serverstring!= null)
Received = true; String NOT NULL, received successfully
if ((receivetime-sendtime) > Delaysecond)
Delaytoolong = true; Receive wait time too long, timeout
}
In.close ();
Out.close (); str=serverstring;
if (Delaytoolong) str= "2190"; Timeout flag is true, return timeout code
if (!received) str = "2190";
Socket.close ();
catch (Unknownhostexception e) {
Log.error ("----> Unknown host error occurred! Host information = "+ This.hostname +" Port number = "
+ this.portnum + "error message =" + E.getmessage ());
str = "2191";
System.exit (1);
catch (IOException e) {
Log.error ("----> IO exception occurred! Host information = "+ This.hostname +" Port number = "
+ this.portnum + "error message =" + E.getmessage ());
E.printstacktrace ();
str = "2191";
catch (Exception e) {
Str= "2177";
Log.error ("----> Unknown exception" + e.getmessage ());
finally {
socket = NULL;
Str.trim ();
Log.info ("---> returned socket communication string =" +str);
return str;
}
}
} -------------------------------------------------------
Socket client establishes connection with Server A, connection B
After the A,b connection is confirmed by the server
A undertakes the work, sends the receiving command to communicate with the service side, simultaneously sends the heartbeat packet to the server every 6 seconds
b Assume the work, accept the service end of the heartbeat packet, 30 seconds to receive the heartbeat packet, to determine the connection is disconnected
Many write custom heartbeat implementation long connection, but no Java aspects of the client's code implementation