NATIONAL TECHNOLOGICAL INSTITUTE OF MEXICO, CAMPUS
ORIZABA
Low-Level Client-Server Programming: sockets and channels
SUBJECT
Client/server environment programming
PRESENTS
Altamirano Cruz Luis Enrique
TEACHER
Pelaez Camarena Silvestre Gustavo
CAREER
COMPUTER ENGINEERING
10th Semester
TOPICS TO PRESENT:
2.1 concept of socket
2.2 domains and types of socket
2.3. creation/implementation and suppression of sockets.
socket opening
2.4. server-side development with sockets
2.5. client-side development with sockets
2.1. Concept of socket.
A socket (plug) is a method for communication between a program.
from the client and a program of theserverin aa red,it is defined, therefore, as the
final point in a connection.
This mechanism emerges in the early80with the systema Unixof Berkeley,
to provide a way dand communicationbetween processes and present the
the same functionality that communication hasemailor by phone (of
a mailbox extracts complete messages, while the phone allows the
sending of information flows that do not have a clearly defined structure
defined), that is to say they allow a process to speak (emit or receive information)
with another even when they are on different machines. This feature of
interconnectivity makes the concept of socket very useful.
A socket is defined by a pair of dIP addresseslocal and remote, a
transport protocol and a pair of local and remote port numbers. For
For two programs to communicate with each other, it is necessary that they meet
certain requirements:
That one program is capable of locating the other.
That both programs are able to exchange any
octet sequence, that is, relevant data to its purpose.
For this, the three resources that originate the concept of socket are necessary:
A communication protocol that allows the exchange of octets.
A couple of addresses of theNetwork Protocol(IP address, if used
the TCP/IP Protocol), which identifies the source computer and the
remote.
A couple of port numbers that identify a program within
each computer.
Sockets allow for the implementation of athe client-server architectureto peer to
peer. Communication must be initiated by one of the programs that
it is called client program. The second program waits for another to start the
communication, for this reason it is called server program.
A socket is a process or thread that exists on the client machine and on the machine
server, which ultimately serves for the server program and the
client lean and write the information. This information will be transmitted by
the different layers of the network.
When a client connects to the server, a new socket is created, in this
the server can continue to wait for connections on the main socket and
communicate with the connected client, similarly a socket is established
on the client on a local port.
Aserver applicationit usually listens on a specific port
waiting for a connection request from a client, once it is received, the
the client and the server connect in a way that allows them to communicate
between both. During this process, the client is assigned a number of
port, through which it sends requests to the server and receives from it the
corresponding answers.
Similarly, the server obtains a new local port number that it
It will serve to continue listening for each connection request on the port.
Likewise, it binds a socket to this local port.
URLs and URLConnections provide a relatively high-level mechanism
level to access resources on the Internet. Sometimes, their programs require
low-level network communication, for example, when you want to write a
client-server application.
In client-server applications, the server provides a service.
such as database query processing or sending prices of
current actions. The client uses the service provided by the server,
either by showing the results of the database query to the user or
making stock purchase recommendations to an investor. The
The communication that occurs between the client and the server must be reliable.
That is to say, no data can be deleted and must reach the client's side in
the same order in which the server sent it.
TCP provides a reliable point-to-point communication channel that the
client-server applications on the Internet use to communicate with each other.
To communicate via TCP, a client program and a program
servers establish a connection with each other. Each program links a socket to
its end of the connection. To communicate, the client and the server read and
write to the socket linked to the connection.
A socket is an endpoint of a two-way communication link between two
programs that run on the network. The socket classes are used to
represent the connection between a client program and a server program. The
The java.net package provides two classes, Socket and ServerSocket, which
they implement the client side of the connection and the server side of the
connection, respectively.
Normally, a server runs on a specific computer and has a
socket that is bound to a specific port number. The server only
wait, listening to a client's socket to make a request for
connection.
On the client side: the client knows the hostname of the machine on the
that the server runs and the port number on which the server is
listening. To make a connection request, the client tries to meet
with the server on the machine and the server port. The client must also
identify with the server, which is linked to a port number
local that will be used during this connection. This is generally assigned by the
system.
If everything goes well, the server accepts the connection. Once accepted, the server
obtains a new socket bound to the same local port and also has its
remote endpoint configured at the client's address and port. Needs
a new footer so that you can continue listening to the original footer in search
of connection requests while attending to customer needs
connected.
On the client side, if the connection is accepted, a socket is successfully created and the
the client can use the socket to communicate with the server.
The client and the server can now communicate by writing to or reading from
sus sockets.
A socket is an endpoint of a two-way communication link between
two programs running on the network. A socket is bound to a
port number for the TCP layer to identify the application that
data is intended to be sent.
A socket is a combination of an IP address and a number of
port. Each TCP connection can be uniquely identified by its two
endpoints. In this way, you can have multiple connections between your host
and the server.
The java.net package in the Java platform provides a class, Socket,
that implements one side of a bidirectional connection between your Java program
and another program on the network. the Plug The class is located above a
platform-dependent implementation, hiding the details of
any particular system of your Java program. Using the
java.net.Socket Instead of relying on native code, your Java programs
they can communicate through the network independently of the
platform.
Additionally, java.net includes the ServerSocket class, which implements
a socket that servers can use to listen for and accept connections
clients. This lesson shows you how to use
the Socket and ServerSocket classes.
Sockets are nothing more than points or mechanisms of communication between
processes that allow a process to speak (emit or receive information) with
another process even with these processes on different machines. This
the characteristic of interconnectivity between machines makes the concept of
sockets are very useful. This communication interface is one of
the Berkeley distributions to the UNIX system, being implemented
interconnectivity utilities of this Operating System (rlogin, telnet,
FTP, ... ) using sockets.
Unsockets the communication system between computers what a mailbox or
a phone is to the communication system between people: a point of
communication between two agents (processes or people respectively) by the
which can emit or receive information.
The way to reference a socket by the involved processes is through
undescriptor of the same type used to reference files. Due to
With this feature, I/O file redirections can be performed.
standard (descriptors 0, 1, and 2) to the sockets and thus combine between them
network applications. Therefore, every new process created will inherit the
socket descriptors of your father.
Communication between processes through sockets is based on the
CLIENT-SERVER philosophy: a process in this communication will act
process server creating a socket whose name the process will know
client, which will be able to "talk" to the server process through the connection
with said socket named.
The process creates an unnamed socket whose return value is a descriptor.
about which it will be read or written, allowing for a
bidirectional communication, a characteristic of sockets that
difference of pipes, or unidirectional communication channels between
processes of the same machine. The communication mechanism via sockets
it has the following steps:
1st) The server process creates a named socket and waits for the connection.
The client process creates an unnamed socket.
The client process makes a connection request to the server socket.
4º) The client makes the connection through its socket while the
The server process maintains the original server socket with name.
It is very common in this type of communication to launch a child process once
once the connection is made, it will handle the exchange of information with the
client process while the parent server process continues accepting
connections. To remove this feature, the socket descriptor will be closed.
server with a name as soon as I establish a connection with a socket process
client.
Every socket is defined by two fundamental characteristics:
The type of socket, which indicates its nature, the type of
communication that can be generated between the sockets.
The socket domain specifies the set of sockets that can
establish communication with him.
Network programming has always been challenging; the programmer had to
know most of the details of the network, including the hardware used,
the different levels in which the network layer is divided, the necessary libraries
to program in each layer, etc.
But the idea simply consists of obtaining information from another
machine, provided by another software application. Therefore, in a way
it can be reduced to the mere act of reading and writing files, with certain
reservations.
The Unix Input/Output system follows the paradigm that normally is
design as Open-Read-Write-Close. Before a user process
it can perform input/output operations, it must make a call to Open
(open) to indicate, and obtain the permissions of the file or device that is
wants to use.
Once the file or device is open, the process of
The user makes one or more calls to Read (read) and Write (write), for the
reading and writing of the data.
The reading process takes data from the object and transfers it to the process.
from the user, while the writing one transfers them from the process of
user to the object. Once the exchange of information is concluded, the
the user process will call Close to inform the operating system
that the use of the file or device has concluded.
In Unix, a process has a set of input/output descriptors from
where to read and where to write. These descriptors may refer to
files, devices, or communication channels sockets.
The life cycle of a descriptor, applied to a communication channel (by
example, a socket), is determined by three phases:
Creation, opening of the socket
Reading and Writing, receiving and sending data through the socket
Destruction, socket closure
The IPC interface in Unix-BSD is implemented over network protocols.
TCP and UDP. The recipients of the messages are specified as
socket addresses; each socket address is an identifier of
communication that consists of an Internet address and a port number.
IPC operations are based on pairs of sockets. They are exchanged.
information transmitting data through messages that circulate between a
socket in one process and another socket in another process. When the messages are
sent, they are queued in the socket until the network protocol has them
broadcasted. When they arrive, the messages are queued in the socket of
reception until the process that has to receive them makes the calls
necessary to collect that data.
The Java language was developed by the company Sun Microsystems around
year 1990, through the creation of a working group headed by
James Gosling. This working group was created to develop a system of
control of appliances and PDAs or personal assistants (small
computers) and that it also had the possibility of interconnecting to networks of
computers. All of this involved the creation of a versatile hardware,
efficient operating system (SunOS) and a development language (Oak). The
the project concluded two years later with a complete failure that led to
the dissolution of the group.
But the development of the project related to the oak language continued thanks to
among other things to the free distribution of language over the Internet through the
incipient, in those years, World Wide Web. In this way the language
reached a certain peak and a large number of programmers took care of it
debugging as well as profiling its shape and uses.
The name Java emerged during one of the brainstorming sessions that
They were celebrated by the language development team. It was necessary to change the
name due to the fact that there was already another language with the name of oak.
Sun MicroSystems launched the first versions of Java in early 1995,
and new versions have been occurring over the last few years,
promoting its use and extending the specifications and its functionality.
One of the most important features of Java is its capability and, at the same time,
ease of creating applications that work over a network. Most of the
low-level implementation details are hidden and are treated in a way
transparent for the JVM (Java Virtual Machine). Programs are
independent of architecture and are executed interchangeably on a large
variety of equipment with different types of microprocessors and systems
operational.
2.2. Domains and Types of sockets.
Types of sockets.
Define the properties of the communications in which a ... is involved.
socket, that is, the type of communication that can occur between client and
server. These can be:
Transmission reliability.
Maintenance of the order of the data.
No data duplication.
The 'Connected Mode' in communication.
Sending urgent messages.
The available types are the following:
Type SOCK_DGRAM: sockets for communications in non-mode
connected, with limited-size datagram sending (telegram type).
In Internet domains such as the one we are dealing with, the protocol of the level of
the transport on which it is based is UDP.
SOCK_STREAM type: for reliable communications in mode
connected, fingers via variable size of data messages. For
underneath, in Internet domains, lies the TCP protocol.
Type SOCK_RAW: allows access to lower-level protocols
like the IP (network level)
SOCK_SEQPACKET type: has the characteristics
of SOCK_STREAM but in addition the size of the messages is fixed.
Each type of socket will define a series of properties based on the
communications in which it is involved:
a) The reliability of the transmission. No transmitted data is lost.
b) The preservation of the order of the data. The data arrives in the order
in which they have been issued.
c) The non-duplication of data. Only one copy of each reaches its destination.
issued date.
d) Communication in connected mode. A connection is established.
between two points before the beginning of communication (that is, it
establish a virtual circuit). From then on, a transmission from
one end is implicitly destined to the other connected end.
e) The preservation of the boundaries of the messages. The boundaries of the
messages emitted can be found at the destination.
f) The sending of messages (urgent). It corresponds to the possibility of
send data outside the normal flow, and consequently accessible
immediately (off-flow data).
It should be noted that a normal communication channel has the first four.
properties, but not the last two.
Regarding the types of available sockets, the following can be considered:
SOCK_STREAM: Sockets of this type allow
reliable communications in connected mode (properties a, b, c and
d) and eventually authorize, according to the applied protocol the
out-of-band messages (property f). The underlying protocol in
The Internet domain is TCP. A virtual circuit is established.
conducting a search for free links that connect the two
computers to connect (similar to what the telephone network does
switched to establish a connection between two phones.
Once the connection is established, one can proceed with the sending.
sequential data, as the connection is permanent. They are
full-duplex byte streams (similar to pipes). A socket stream
must be in connected state before sending or receiving in
he.
* SOCK_DGRAM: Corresponds to the sockets intended for the
communication in disconnected mode for the sending of datagrams
of limited size. The corresponding communications have
the property e. In the Internet domain, the underlying protocol is
UDP. Datagram packets do not work with connections.
permanent. The transmission through the datagrams is at the level of
packages, where each package can follow a different route, not
ensuring a sequential reception of the information.
* SOCK_RAW: Allows access to the lowest level protocols
level (for example, the IP protocol in the Internet domain). Its
use is reserved for the superuser.
SOCK_SEQPACKET: Corresponds to communications that
possess properties a, b, c, d, and e. These communications are
they are found in the XNS domain.
The two most commonly used types of sockets are the first two.
The domain of a socket.
Indicate the format of the addresses that sockets can take and the
protocols that will support such sockets.
The generic structure is
struct sockaddr {
u__short sa__family; family
charactersa__data[14]; /* address */
};
They can be:
UNIX Domain (Address Family UNIX):
The client and the server must be on the same machine. It must
include the header file /usr/include/sys/un.h. The structure of a
the address in this domain is:
struct sockaddr__un {
short sun__family; /* in this case AF_UNIX */
character sun__data[108]; /* address */
};
DomainAF_INET (Address Family INET):
The client and the server can be on any machine in the network.
Internet. The header files /usr/include/netinet/in.h must be included,
/usr/include/arpa/inet.h, /usr/include/netdb.h. The structure of a
address in this domain is:
struct in__addr {
unsigned long s_addr;
};
struct sockaddr__in {
short sin_family; /* in this case AF_INET */
u__short sin_port; /* port number */
struct in__addr sin__addr; /* Internet address */
char sin_zero[8]; /* field of 8 zeros */
};
These domains are going to be used in xshine. But there are others.
as:
* DominioAF_NS:
Server and client must be on a XEROX network.
DominioAF_CCITT
For CCITT protocols, X25 protocols, ...
A family, or domain of connection, groups all those sockets that
they share common characteristics. Specify the format of the addresses
that can be given to the socket and the different protocols supported by the
communications via the sockets of this domain.
Each protocol, when referring to a node in the network, implements a
addressing mechanism. The address unambiguously distinguishes
each node or computer, and it is used to route data from the node
origin to the destination node. There are many system calls that need
a pointer to a socket address structure to work with. The following
generic structure, is used to describe the different primitives.
struct sockaddr {
u_short sa_family; /* socket family; used
constants of the form AF_xxx */
char sa_data[14]; /* 14 bytes that contain the
direction; its meaning depends on the family of
sockets that are used */
};
But in the case that we are dealing with a particular application, this
the structure must be replaced by the corresponding domain structure
of communication used, since unfortunately, not all families of
directions fit the described generic structure.
Nevertheless, this generic structure fits into the defined structure for the
AF_INET family, belonging to the Internet domain, which makes it
TCP/IP software works correctly even if the programmer uses the
previous generic structure, since both have the same number of
bytes. Next, we proceed to describe this domain structure.
Internet.
struct sockaddr_in {
short sin_family; /* the address family
AF_INET*
u_short sin_port; /* 16 bits with the number of the
port
u_long sin_addr; /* 32 bits with the address
Internet (network and host identification)
char sin_zero[8]; /* 8 unused bytes */
It can be observed that in the Internet address the field sin_family is
equivalent to the sa_family field of the generic address and that the fields
sin_port, sin_addr, and sin_zero serve the same function as the field
sa_addr.
We can also see the UNIX domain (AF_UNIX), where the sockets are
locales to the system in which they have been defined. They allow communication
internal processes, and their designation is made through a reference
UNIX.
struct sockaddr_un {
short sun_family; /* UNIX domain:
AF_UNIX */
char sun_data[108]; /* path */
};
These addresses actually correspond to file paths, and their
length (110 bytes) is greater than the standard 16 bytes they have.
the addresses of the rest of the families. This is possible because this family
it is used to communicate processes executed under the control of the same machine,
not having to access the network. Other domains are:
AF_NS /* XEROX NS protocols */
AF_CCITT /* CCITT protocols, X.25 protocols, etc. */
AF_SNA /* IBM SNA */
AF_DECnet /* DECnet */
2.3. Creation/implementation and deletion of sockets.
Opening Sockets
If we are programming a CLIENT, the socket is opened in the following way:
Socket myClient;
myClient = new Socket("machine", portNumber);
Where machine is the name of the machine we are trying to open.
the connection and portNumber is the port (a number) of the server that is
running on which we want to connect. When a is selected
port number, it should be taken into account that ports in the range 0-1023
they are reserved for users with many privileges (superusers or root).
These ports are the ones used by the system's standard services such as
email, ftp or http. For the applications being developed, ensure that
select a port above 1023.
In the previous example, exceptions are not used; however, it is a great idea.
the exception handling when working with sockets. The same
example would be like:
Socket myClient;
try {
myClient = new Socket("machine", portNumber);
IOException caught
System.out.println( e );
}
If we are programming a SERVER, the way to open the socket is the
shows the following example:
Socket myService;
try {
myService = new ServerSocket( portNumber );
} catch( IOException e ) {
System.out.println( e );
}
When implementing a server, we also need to create a
socket objects from the ServerSocket to be on the lookout for connections that
potential customers can connect and be able to accept those connections:
Socket socketService = null;
try {
socketService = myService.accept();
} catch( IOException e ) {
System.out.println( e );
}
Creation of Input Streams
In the CLIENT part of the application, the class can be used
DataInputStream to create an input stream that is ready to receive all
the responses that the server sends you.
DataInputStream input;
try {
input = new DataInputStream( myClient.getInputStream() );
} catch( IOException e ) {
System.out.println( e );
}
The DataInputStream class allows for reading lines of text and data types.
Java primitives in a highly portable way; it has methods for
read all those types like: read(), readChar(), readInt(), readDouble() and
readLine(). We will need to use the function we created as necessary depending on
of the data type that we expect to receive from the server.
On the SERVER side, we will also use DataInputStream, but in this
case to receive the entries that occur from the clients who have
connected
DataInputStream input;
try {
entrada
new DataInputStream(socketService.getInputStream());
} catch( IOException e ) {
System.out.println( e );
}
Creation of Output Streams
On the CLIENT side, we can create an output stream to send
server socket information using the PrintStream or classes
DataOutputStream:
PrintStream output;
try {
output = new PrintStream( myClient.getOutputStream() );
} catch( IOException e ) {
System.out.println( e );
}
The PrintStream class has methods for the textual representation of all
primitive data types in Java. Their methods write and println() have a special
importance in this aspect. However, for sending information to
server we can also use DataOutputStream:
DataOutputStream output;
try {
output = new DataOutputStream( myClient.getOutputStream() );
} catch( IOException e ) {
System.out.println( e );
}
The DataOutputStream class allows writing any of the primitive types
In Java, many of its methods write a primitive data type in the
output stream. Of all those methods, perhaps the most useful is writeBytes().
On the SERVER side, we can use the PrintStream class to send
customer information:
PrintStream output;
try {
output = new PrintStream( socketService.getOutputStream() );
Socket Closure
We should always close the input and output channels that have been opened.
during the execution of the application.
On the client side:
try {
output.close();
input.close();
myClient.close();
} catch( IOException e ) {
System.out.println( e );
}
And on the server side:
try {
output.close();
input.close();
socketService.close();
myService.close();
} catch( IOException e ) {
System.out.println( e );
}
It is important to highlight that the closing order is relevant. That is to say, it must be
close first the streams related to a socket before the socket itself
socket, since this way we avoid possible errors in writing or reading
about closed descriptors.
Useful classes in communications
Socket
It is the basic object in all communication over the Internet, under the
TCP protocol. This class provides methods for input/output through
the streams that make reading and writing through sockets very simple.
ServerSocket
It is an object used in server applications to listen to requests.
that connected clients perform on that server. This object does not perform the
service, but creates a Socket object based on the client to carry out
all communication through him.
DatagramSocket
The datagram socket class can be used to implement
unreliable datagrams (UDP sockets), unordered. Although the communication
through these sockets it is very fast because you don't have to waste time
establishing the connection between client and server.
DatagramPacket
Class that represents a datagram packet containing information of
packet, packet length, Internet addresses, and port numbers.
MulticastSocket
Class used to create a multicast version of the datagram socket class.
Multiple clients/servers can transmit to a multicast group (a group
of IP addresses sharing the same port number).
NetworkServer
A class created to implement methods and variables used in the
creation of a TCP/IP server.
NetworkClient
A class created to implement methods and variables used in the
creation of a TCP/IP client.
SocketImpl
It is an interface that allows us to create our own model of
communication. We will have to implement its methods when we use it. If
we are going to develop an application with special requirements of
communications, such as the implementation of a firewall (TCP
it is an unsecured protocol), or access special equipment (such as a reader of
barcode or a differential GPS), we will need our own class
Socket.
2.4. Server-side development with sockets.
Writing the server side of a socket
This section shows you how to write a server and the client that it
accompanies. The server in the client/server pair serves to make jokes about
Knock Knock. Knock Knock jokes are preferred by children and
they are usually vehicles for bad puns. They go like this:
Server: "Knock knock!"
Client: "Who is there?"
Server: "Dexter".
Client: 'Dexter who?'
Server: 'Dexter rooms with holly branches.'
Client: "Groan".
The example consists of two Java programs that run simultaneously.
independent: the client program and the server program. The program
the client is implemented by a single class, KnockKnockClient, and is very
similar to the EchoClient Example from the previous section. The program of the
the server is implemented by two classes: KnockKnockServer and
KnockKnockProtocol, KnockKnockServer contains the main method
for the server program and performs the task of listening on the port,
establish connections and read and write in the
socket. KnockKnockProtocol Serves the jokes. Keeps track of
the current joke, the current state (ordered to beat, sent a clue, etc.) and
returns the different parts of the joke according to the current state. This
object implements the protocol, the language that the client and the server have
agreed to use for communication.
The following section examines in detail each class, both in the client and in
the server, and then shows you how to run them.
The Knock Knock server
This section describes the code that implements the server program
Knock Knock. Here is the full source for
theKnockKnockServerclass.
The server program starts by creating a new ServerSocket object
to listen on a specific port (see the bold statement in the
next segment of code). When writing a server, choose a port that is still
is not dedicated to any other service. KnockKnockServer listens on the
Port 4444 is now my favorite number and port 4444 is not
being used for anything else in my environment:
to try
serverSocket = new ServerSocket(4444);
}
catch (IOException e) {
Could not listen on port: 4444
System.exit (-1);
}
ServerSocket is a java.net class that provides an implementation
independent of the server-side system of a socket connection
client / server. The constructor for ServerSocket throws an exception if not
can listen on the specified port (for example, the port is already
using). In this case, the KnockKnockServer has no choice but to
to leave.
If the server successfully connects to its port, then
the ServerSocket object was created correctly and the server continues with
the next step: accept a connection from a client (shown in bold):
Socket clientSocket = null;
to treat {
clientSocket = serverSocket.accept();
}
catch (IOException e) {
System.out.println ("Acceptance error: 4444");
System.exit (-1);
}
Accept the method waits until a client starts and requests a
connection on the host and the port of this server (in this example, the server is
is running on the hypothetical machine Taranis on port 4444). When
a connection is requested and successfully established, the acceptance method
returns a new Socket object that is bound to the same local port
and has its remote address and remote port set to that of the client.
The server can communicate with the client through this.
new Plug and keep listening to the customer's connection requests in
the original ServerSocket This particular version of the program does not listen
more customer connection requests. However, a modified version
the program is provided inSupport for multiple clients.
Once the server successfully establishes a connection with a client, it
communicate with the client using this code:
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in =
new BufferedReader (new InputStreamReader
(clientSocket.getInputStream ()));
String inputLine
start the conversation with the client
KnockKnockProtocol kkp = new KnockKnockProtocol();
outputLine = kkp.processInput(null);
out.println(outputLine);
while ((inputLine = in.readLine()) != null) {
outputLine = kkp.processInput(inputLine);
out.println(outputLine);
if (outputLine.equals ("Bye."))
rest
}
This code:
1. Obtains the input and output stream of the socket and opens readers and
writers in them.
2. Start communication with the client by writing to the socket (it
(show in bold).
3. Communicates with the client by reading and writing to the socket
(he while loop).
Step 1 is already familiar. Step 2 is shown in bold and is worth a few.
comments. The bold statements in the previous code segment
they start the conversation with the client. The code creates
a KnockKnockProtocol object: the object that keeps track of the
current joke, the current state within the joke, etc.
After the KnockKnockProtocol is created, the code
llama. KnockKnockProtocol's entry process Method to obtain the
first message that the server sends to the client. For this example, the first
what the server says is "Knock! Knock!" Next, the server writes the
information to the PrintWriter connected to the client's socket, thus sending the
message to the client.
Step 3 is encoded in the while loop. While the client and server
they still have something to say to each other, the server reads and writes to the socket, sending
messages between the client and the server.
The server started the conversation with a "Knock! Knock!" so then the
the server must wait for the client to say 'Who's there?' As a result,
the while loop repeats in a read from the input stream. The method
readLine waits for the client to respond by writing something in their stream
output (the server's input flow). When the client responds, the
server passes the client's response to the KnockKnockProtocol object and
ask the KnockKnockProtocol object for an appropriate response. The
server immediately sends the response to the client through the stream of
output connected to the socket, using a call to print. If the
the server response is generated from the KnockKnockServer The object is
"Bye". This indicates that the client does not want any more jokes and the loop closes.
the KnockKnockServer class is a well-behaved server, so the
that the last lines of this KnockKnockServer section clean up
closing all input and output streams, the client socket and the socket
from the server:
fuera.close();
search();
clientSocket.close();
serverSocket.close();
The Knock Knock Protocol
TheKnockKnockProtocolThe class implements the protocol that the client and
the server is used to communicate. This class tracks
where the client and the server are in their conversation and presents the
server's response to the client's statements.
the KnockKnockServer object contains the text of all the jokes and is
ensure that the customer gives the appropriate response to the statements of the
server. It wouldn't be good if the client said 'Dexter who?' when he
server says 'Knock! Knock!'
All client/server pairs must have some protocol by which
they speak to each other; otherwise, the data that passes from one side to the other does not
would make sense. The protocol used by their own clients and servers
a car return, the customer sends the text to the server through the sequence
output attached to the socket.
while ((fromServer = in.readLine()) != null) {
System.out.println("Server:" + server);
if (fromServer.equals("Bye."))
rest;
fromUser = stdIn.readLine();
if (fromUser != null) {
System.out.println("Customer:" + User);
out.println (fromUser);
}
}
The communication ends when the server asks if the client wants
listen to another joke, the customer says no and the server says 'Goodbye'.
In the interest of good maintenance, the client closes their incoming flows and
exit and the socket:
fuera.close();
search();
stdIn.close();
kkSocket.close();
Running the programs
You must start the server program first. To do this, run the
server program using the Java interpreter, as I would do with
any other Java application. Remember to run the server on the machine
that the client program specifies when it creates the socket.
Next, run the client program. Note that you can
run the client on any machine in your network; it does not have to run on
the same machine as the server.
If it's too fast, it may start the client before the server has
the opportunity to initialize and start listening on the port. If this
It happens, you will see a follow-up of the client stack. If this happens, just
restart the client.
If you forget to change the host name in the source code for
the KnockKnockClient program, you will see the following error message:
I don't know about the host: taranis
To fix this, modify the KnockKnockClient program and provide
a valid host name for your network. Recompile the client program and return.
to try it.
If you try to start a second client while the first client is connected
to the server, the second client simply crashes. The next
sectionSupport for multiple clientstalks about multi support
clients.
When successfully establishing a connection between the client and the server, you will see the
next text displayed on your screen:
Server: Knock! Knock!
Now, you must respond with:
Who is there?
The client reflects what it writes and sends the text to the server. The server
Knock, knock.
in its repertoire. Now your screen should contain this (the text you wrote
is in bold):
Server: Knock! Knock!
Who is there?
Client: Who is there?
Server: Turnip
Now, you respond with:
Who is Naboo?
Once again, the client echoes what is written and sends the text to the server.
The server responds with the drilling line. Now your screen should
contain this:
Server: Knock! Knock!
Who is there?
Client: Who is there?
Server: Turnip
Who is the neighbor?
Client: Turnip who?
Server: Turn off the heat, it's cold here! Do you want another one? (y / n)
If you want to hear another joke, write y; if not, write n. If you write y,
the server starts again with 'Knock! Knock!' If you type n, the
the server says 'Bye'. causing both the client and the server to exit.
If at any point you make a writing error, the KnockKnockServer the
the object traps it and the server responds with a message similar to this:
Server: you're supposed to say 'Who's there?'
The server is playing the joke again:
Server: try again. Bang! Bang!
Please note that the KnockKnockProtocol object is particular about the
spelling and punctuation, but not about the use of capital letters.
2.5. Client-side development with sockets
Reading and writing from a socket
Let's look at a simple example that illustrates how a program can establish
a connection to a server program using the Socket class and then,
how the client can send and receive data from the server through the socket.
The example program implements a client, EchoClient, that connects to the
Echo server. The Echo server simply receives data from its client and
returns. The Echo server is a well-known service that clients
They can be found at port 7.
EchoClient creates a socket to obtain a connection with the Echo server.
Read the user input from the standard input stream and then send
this text to the Echo server by writing the text in the socket. The server repeats
the new entry through the socket to the client. The client program reads and
show the data that is returned from the server:
import java.net.*;
public class EchoClient {
public static void main (String [] args) throws IOException {
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
deal
echoSocket = new Socket("taranis", 7);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader (new InputStreamReader (
echoSocket.getInputStream());
} catch (UnknownHostException e) {
System.err.println("I don't know about host: taranis.");
System.exit (1);
} catch (IOException e) {
System.err.println("Could not get I/O for")
the connection to: taranis.
System.exit (1);
}
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(System.in));
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println (userInput);
System.out.println("echo:" + in.readLine());
}
fuera.close();
search();
stdIn.close();
echoSocket.close();
}
}
Please note that EchoClient writes and reads from its socket, sending
data to the Echo server and receiving data from it.
Let's look at the program and investigate the interesting parts. The three
statements in the main block of the treatment The method is critical. These
lines establish the socket connection between the client and the server and open
a PrintWriter and a BufferedReader in the socket:
echoSocket = new Socket("taranis", 7);
out = new PrintWriter (echoSocket.getOutputStream (), true);
in = new BufferedReader(new InputStreamReader
(echoSocket.getInputStream ());
The first statement in this sequence creates a new Plug object and
it is named echoSocket. The plug The constructor used here requires
the name of the machine and the port number you want to connect to. The
example program uses the host name taranis. This is the name of a
hypothetical machine on our local network. When you write and execute this
program on your machine, change the host name to the name of a
machine on your network. Make sure the name you use is the IP name.
complete of the machine you wish to connect to. The second argument is the
port number. Port number 7 is the port on which it listens
Echo server.
The second statement obtains the socket's output flow and opens
a PrintWriter in that. Similarly, the third instruction obtains the
incoming socket flow and opens a BufferedReader on it. The example
use readers and writers so that I can write Unicode characters in the
socket.
To send data through the socket to the server, EchoClient simply
You have to write to the PrintWriter. To get the response from the
server, EchoClient reads from the BufferedReader. The rest of the program does
Get it. If you are not yet familiar with the I/O classes of the platform
Java can readI / The basics.
The next interesting part of the program is the while loop. The loop reads
one line at a time from standard input and sends it immediately
to the server by writing it in the PrintWriter connected to the socket:
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("echo:" + in.readLine());
}
The last statement in the while loop reads a line of information from
the BufferedReader connected to the socket. the readLine method waits
until the server returns the information to EchoClient.
When readline returns, EchoClient prints the information to the
standard output.
the loop continues until the user types a character of
end of input. That is, EchoClient reads the user's input, sends it to the
Echo server, receives a response from the server and displays it until it arrives
at the end of the entry. while then the loop ends and the program
continue, executing the following four lines of code:
fuera.close();
search();
stdIn.close();
echoSocket.close();
These lines of code fall into the category of cleanup. A program of
good behavior always cleans up after itself, and this program
he/she has good behavior. These statements close the readers and
writers connected to the socket and standard input stream, and close the
socket connection to the server. The order here is important. You must close all
the sequences connected to a socket before closing the socket.
This client program is simple and straightforward because of the Echo server.
implement a simple protocol. The client sends text to the server, and the
the server repeats it. When its client programs are talking to a
more complicated server like an HTTP server, its client program
it will also be more complicated. However, the basic concepts are very
similar to those of this program:
Open a socket.
2. Open an input stream and an output stream to the socket.
Read and write in the stream according to the server protocol.
Close the streams.
Close the baseboard.
Only step 3 differs from client to client, depending on the server. The others
the steps remain largely the same.