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

Socket()

Creates an unconnected socket.

Socket(InetAddress address, int port)

Creates a socket and connects it to the specified address and port.

Socket(String host, int port)

Creates a socket and connects it to the specified host and port.

Methods

Method

Description

void Close()

Closes the socket.

void connect(Inet SocketAddress endpoint)

Connects the socket to the specified address.

InetAddress getInetAddress()

Gets the address to which the socket is connected.

InputStream getInputStream()

Gets an input stream that can be used to receive data sent through this socket.

OutputStream getOutputstream()

Gets an output stream that can be used to send data through this socket.

int getPort()

Gets the port to which this socket is connected.

boolean isBound()

Indicates whether the socket is bound to a port.

boolean isClosed()

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

Get Java For Dummies Quick Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.