简体   繁体   中英

State of a new Java socket

When I declare in Java

Socket s = new Socket((String)null, 12345);

Does this actually open a socket and use system and network resources, or is that deferred until I attach an input/output buffer? I would like to create a Socket object at the start of my program that is all set up to connect to the server, and just open/close it as necessary, instead of having to pass an address and port around (it seems cleaner), but not if it means the port will be open the entire time.

EDIT
It seems from the answers that this will not work like I wanted. How can I create a closed socket that is all set up with address and only needs to connect?

http://docs.oracle.com/javase/6/docs/api/java/net/Socket.html#Socket(java.net.InetAddress,%20int) <- it depends on the constructor you use. For the constructor you have specified, it connects.

For your edit: You will have to set up your own class that holds all setup information and can then be opened later. Maybe yüu'll just store the data in there and make a method that returns a socket. It's up to you, there's plenty ways to do that. But make sure all sockets were correctly closed at the end ;)

Every constructor of Socket creates an underlying socket, which uses system resources, and all but the no-args constructor connect it as well, which uses network resources. There is no such operation as 'attach[ing] an input/output buffer' to a Socket.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM