////The socket created by the parameter constructor will access the network, and no parameter will
Socket socket=new socket ("www.baidu.com", 80);
//When the local port is 0 it indicates that the port is randomly assigned by the system
Socket socket=new socket ("www.baidu.com", 80,inetaddress.getbyname ("localhost"), 0);
Socket socket = new socket ();
The Connect method also allows you to specify the time-out for the connection, and the socket setting is best to call the relevant method before the Connect method
Socket.connect (New Inetsocketaddress (Inetaddress.getbyname ("www.baidu.com"), 80), 5000);
try {
if (socket!=null) {
//socket is closed because the client may be shut down so that it will be abnormal, then do not handle the exception
Socket.close ();
}
} catch (Exception e) {
}
//socket can obtain relevant information even if it is closed
System.out.println (Socket.getinetaddress ());
//Determine if the Sokcet is connected to a remote machine
System.out.println (socket.isconnected ());
//Determine if the socket is closed, the socket is not connected and returns false
System.out.println (socket.isclosed ());
//correctly determine if the socket is open
System.out.println (socket.isconnected () &&!socket.isclosed ());
//Determine if the socket is bound to a local port
System.out.println (Socket.isbound ());
//Get input and output streams, get remote data and send data to remote, and when any one of them shuts down, the socket will also close
Socket.getinputstream ();
Socket.getoutputstream ();
The input and output streams are automatically closed when the//socket is closed, and the following method only closes the associated stream
Socket.shutdowninput ();
Socket.shutdownoutput ();
//Set read data time-out time, unit Ms
Socket.setsotimeout (1000);
//The object can be recycled after the socket is closed and then reused
SocketAddress address=new inetsocketaddress ("www.baidu.com", 80);
Java Network Programming 3-socket