Reputation: 1721
Although ServerSocket class is designed to generically listen for incoming connections, Can I just use a Socket object instead and retrieve incoming data in java? If yes, then is there any additional precautions that i need to take in doing so?
Edit: Thanks for the answers...but although in UDP there is only one socket class--DatagramSocket right?
Upvotes: 2
Views: 202
Reputation: 1105
Socket cannot receive incoming connections: only ServerSocket can do this.
Upvotes: 3
Reputation: 43907
When using sockets one end has to reach out and connect to the other end (and the other end must be listening for that connection). The end that is reaching out is typically called the client. The end that is listening is called the server.
A ServerSocket represents that listening behavior. Once your ServerSocket receives a connection it will create a Socket. So you actually need to use both. The server first sets up a ServerSocket and then waits for a connection using accept(). This will create a Socket once the connection has arrived.
In some applications the server keeps waiting for more connections, in other applications you can decommission the ServerSocket at this point and just worry about the Socket.
Unfortunately you can't have clients on both sides (unless you have a 3rd server which both are connecting to) because someone has to be listening for connections.
Upvotes: 2
Reputation: 21912
The ServerSocket
is used to bind() and accept() to a local port. Despite the name, ServerSocket
is not a Socket
, it's only used to receive the connection. Once that's done, you get a Socket
from accepting an incoming request, that is a communication pipe. I don't believe you can use a Socket
to receive incoming requests without using some sort of connection receiver like ServerSocket
.
Upvotes: 5