Java Network Programming 3-socket

Source: Internet
Author: User

////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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.