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


What is a Socket?

Mail, ftp, telnet, name and finger are all examples of services provided by computers on the network. Typically, each service is served up on a dedicated, well-known port. [PENDING: define port]. Your programs can access a specific service by connecting to the port dedicated to that service. This is similar to real-life--when you need to have your clothes dry-cleaned you go to the drycleaner, when you need to get money you go to the bank, and so on. In addition to the ports that are dedicated to specific services, computers also have other ports that let programmers create their own services.

Ports are typically numbered and your program can connect to a port by specifying the port number of the service you wish to connect to. Each service or port recognizes a certain protocol--you must formulate your requests in a manner specific to that service in order for your request to be understood and responded to.

Try this: Locate and view the services file on your computer which lists all of the services provided by your system and the port numbers corresponding to those services. What is the port number for mail? For ftp?


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

Your client program can write requests to the socket, and the server will process your request and return the results back to you via the socket. Try this: If you have access to a command line version of the telnet program, use it to connect to port #13 on your computer. What happened? What service is provided on port #13 on your computer?

Sockets are low-level connections. The client and the server both communicate through a stream of bytes written to the socket. 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.

If you are trying to connect to the World Wide Web, the URL class and related classes (URLConnection, URLEncoder) are probably more suitable 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.

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.

See also

java.net.ServerSocket
java.net.Socket


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