Socket Class
The Socket
class represents a socket connection between two programs. Socket connections allow two computers to connect and exchange information. Although the programs can be running on the same computer, they don’t have to be. In fact, any two computers that are connected to the Internet can communicate via a socket.
Constructors
Constructor |
Description |
|
Creates an unconnected socket. |
|
Creates a socket and connects it to the specified address and port. |
|
Creates a socket and connects it to the specified host and port. |
Methods
Method |
Description |
|
Closes the socket. |
|
Connects the socket to the specified address. |
|
Gets the address to which the socket is connected. |
|
Gets an input stream that can be used to receive data sent through this socket. |
|
Gets an output stream that can be used to send data through this socket. |
|
Gets the port to which this socket is connected. |
|
Indicates whether the socket is bound to a port. |
|
Indicates whether the socket is closed. |
Creating a socket
Although the Socket
class has constructors that let you connect to a specific address, the normal way to create a socket is to use the accept
method of the ServerSocket
class like this:
int port = 1234;
ServerSocket ss = new ServerSocket(port);
Socket s = ss.accept();
The preceding example suspends the thread until a client connects on port 1234. Then, a Socket
object is created via which the programs can communicate.
Sending data via a socket
The getOutputStream
method returns an object of the OutputStream
class. Note that the PrintStream
class constructor can accept an OutputStream
object. Thus, you can use PrintStream
to send data to a client program.
For example, the following code sends the text HELO
to a client connected via a socket:
int port = 1234;
ServerSocket ss = new ServerSocket(port);
Socket s = ss.accept();
PrintStream out;
out = new PrintStream(s.getOutputStream(),
true);
out.println(“HELO”);
Receiving data via a socket
The getInputStream
method returns an InputStream
object, which can be used to receive data sent from a client program. You can then use classes such as StreamReader
or Scanner
to receive data from the socket.
For example, here’s a bit of code that connects to a client computer and waits until it receives the text HELO
before continuing:
int port = 1234;
ServerSocket ss = new ServerSocket(port);
Socket s = ss.accept();
Scanner in = new Scanner(s.getInputStream());
String input = “”;
while (input != “HELO”)
input = in.nextLine();
// code to execute after “HELO” is received