Previous | Next | Trail Map | Custom Networking and Security | All About Sockets


What Is a Socket?

A server application normally listens to a specific port waiting for connection requests from a client. When a connection request arrives, the client and the server establish a dedicated connection over which they can communicate. During the connection process, the client is assigned a local port number, and binds a socket to it. The client talks to the server by writing to the socket and gets information from the server by reading from it. Similarly, the server gets a new local port number (it needs a new port number so that it can continue to listen for connection requests on the original port). The server also binds a socket to its local port and communicates with the client by reading from and writing to it.

The client and the server must agree on a protocol--that is, they must agree on the language of the information transferred back and forth through the socket.


Definition: A socket is one end-point of a two-way communication link between two programs running on the network.

The java.net package in the Java development environment provides a class--Socket--that represents one end of a two-way connection between your Java program and another program on the network. The Socket class implements the client side of the two-way link. If you are writing server software, you will also be interested in the ServerSocket class which implements the server side of the two-way link. This lesson shows you how to use the Socket and ServerSocket classes.

If you are trying to connect to the World Wide Web, the URL class and related classes (URLConnection, URLEncoder) are probably more suitable than the socket classes to what you are doing. In fact, URLs are a relatively high level connection to the Web and use sockets as part of the underlying implementation. See Working with URLs(in the Networking trail)for information about connecting to the Web via URLs.

See also

java.net.ServerSocket
java.net.Socket


Previous | Next | Trail Map | Custom Networking and Security | All About Sockets