[Solved] Difference between two code

What is the difference between

ServerSocketChannel server = ServerSocketChannel.open()
server.bind(new InetAddress(55555))

and

ServerSocketChannel server = ServerSocketChannel.open()
server.socket.bind(new InetAddress(55555))

The reason that i ask because i see the latter so much

Both do probably the same. ServerSocketChannel is just a wrapper around ServerSocket to give you access to the NIO Channel API. I don’t know why anyone would use the second code, although it is kind of documented implementation detail that ServerSocketChannel relies on ServerSocket, but I think it is no good practise to rely on implementation detail of an interface one uses.

The second snippet is also more to write^^

They both essentially do the same thing. The first method requires java 1.7 since the bind() method in ServerSocketChannel uses the NetworkChannel interface that was added in 1.7 while the second method uses the sockets (ServerSocket) bind() method directly which is compatible with java 1.4

http://docs.oracle.com/javase/7/docs/api/java/nio/channels/NetworkChannel.html

http://docs.oracle.com/javase/7/docs/api/java/nio/channels/ServerSocketChannel.html#bind(java.net.SocketAddress)

http://docs.oracle.com/javase/7/docs/api/java/net/ServerSocket.html#bind(java.net.SocketAddress)

Openjdk 7 links:

http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7-b147/java/nio/channels/NetworkChannel.java#NetworkChannel.bind(java.net.SocketAddress)

http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7-b147/java/nio/channels/ServerSocketChannel.java?av=f

Comparing openjdk’s (6b14) implementation the former goes through the security manager for verification whilst the latter just connects immediately.

http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/net/Socket.java

http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/net/ServerSocket.java#ServerSocket.bind(java.net.SocketAddress)

sry, but I think you got something mixed up. This is not about Socket.java but ServerSocket.

I took a look, and it seems to be something else entirely. As I though ServerSocketChannel is the “new” NIO way to do it, but it doesn’t wrap the old ServerSocket. When you call the socket() method it returns a wrapper object of the Channel which behaves like an old ServerSocket.

So, use the first code snippet. The second one is only there for backwards compatibility. Like if you have to use code which needs the old ServerSocket, but you want to use the new ServerSocketChannel.

Yes you’re half right, the ServerSocket checks the Security Manager if it exists as well.