Java Reference
In-Depth Information
3.
After the server is waiting, a client instantiates a Socket object, specify-
ing the server name and port number to connect to.
4.
The constructor of the Socket class attempts to connect the client to the
specified server and port number. If communication is established, the
client now has a Socket object capable of communicating with the
server.
5.
On the server side, the accept() method returns a reference to a new
socket on the server that is connected to the client's socket.
When a client establishes a socket connection to a server, the client needs
to specify a port number. This port number denotes the port that the
server is listening on. However, after a client and server are connected
using sockets, their connection is actually taking place on a different port.
This allows the server, in a separate thread, to continue listening on the
original port for other clients. This all takes place behind the scenes and
should not affect your code, but it is an important tidbit to understand.
After the connections are established, communication can occur using I/O
streams. Each socket has both an OutputStream and an InputStream. The
client's OutputStream is connected to the server's InputStream, and the
client's InputStream is connected to the server's OutputStream. TCP is a two-
way communication protocol, so data can be sent across both streams at the
same time.
The socket streams are low-level I/O streams: InputStream and
OutputStream. Therefore, they can be chained together with buffers,
filters, and other high-level streams to allow for any type of advanced I/O
you need to perform. This is why I discussed the java.io package before
network programming. You are about to find out that creating the
connection is the easy part, and most of your work in network
programming involves the actual transmitting of data back and forth. Of
course, this is how network programming should be, allowing you to
focus on the problem being solved and not worrying about the low-level
communication and protocol details. This is one of the reasons why Java
is so popular among network programmers.
Let's look at an example using sockets. I will start with a program that runs
on the server, listening on a port for client requests. Then I will show you how
to write the client code that connects to the server application.
Search WWH ::




Custom Search