Chapter 5
Networking /
Socket
Programming
Contents
Introduction
Client/Server Computing
Server Sockets
Client Sockets
Data Transmission through Sockets
A Client/Server Example
The InetAddress Class
Serving Multiple Clients
Sending and Receiving Objects
Introduction
IP Address:
To communicate each other computer, they should have unique address.
An Internet Protocol (IP) address uniquely identifies computers on the Internet.
IP is a protocol for delivering data from one computer to another across the Internet in packets.
Two higher-level protocols are used in conjunction with the IP:
the Transmission Control Protocol (TCP) and
the User Datagram Protocol (UDP).
TCP guarantees delivery of data and also guarantees that packets will be delivered in the same order in
which they were sent.
UDP is a standard, low-overhead, connectionless, host-to-host protocol that is used over the IP.
Java supports both stream-based and packet-based communications.
Stream-based communications use TCP for data transmission.
packet-based communications use UDP.
Since TCP can detect lost transmissions and resubmit them, transmissions are lossless and reliable.
UDP, in contrast, cannot guarantee lossless transmission.
Stream-based communications are used in most areas of Java programming and are the focus of this
chapter.
Client / Server Computing
Java provides two important class:
ServerSocket – class for creating a server socket and
Socket – class for creating a client socket.
Both classes are in package [Link] You need to import them from this package.
Two programs on the Internet communicate through a server socket and a client socket using
I/O streams.
Sockets are the endpoints of logical connections between two hosts and can be
used to send and receive data.
Programs can read from or write to sockets the same way they read from or write
to files.
Network programming usually involves a server and one or more clients.
The client sends requests to the server, and the server responds, i.e.
The client begins by attempting to establish a connection to the server.
The server can accept or deny the connection.
Once a connection is established, the client and the server communicate through sockets.
The server must be running when a client attempts to connect to the server.
Client / Server Computing
A socket is one endpoint of a two-way communication link between two programs
running on the network.
A socket is bound to a port number so that the TCP layer can identify the
application that data is destined to.
An endpoint is a combination of an IP address and a port number.
Every TCP connection can be uniquely identified by its two endpoints. That way
you can have multiple connections between your host and the server.
The Socket class, implements one side of a two-way connection between your
Java program and another program on the network.
The Socket class sits on top of a platform-dependent implementation, hiding the details of the
underlying system.
By using the Socket class, your Java programs can communicate over the network in a
platform-independent fashion.
The ServerSocket class implements a socket that servers can use to listen for and
accept connections to clients.
Client / Server Computing
Simple steps for creating Client/Server Computing is
1. The Server creates a socket bound to a specific port number
2. The Server listens to the socket for a client to make connection.
3. The client tries to connect to the server by specifying the hostname (IP) and port
number on which the server is running.
4. If everything goes well, the server accepts the connection
Upon acceptance, the server gets a new socket bound to the same local port and also has its
remote endpoint set to the address and port of the client.
It needs a new socket so that it can continue to listen to the original socket for connection
requests while tending to the needs of the connected client.
5. On the client side, if the connection is accepted, a socket is successfully created
and the client can use the socket to communicate with the server.
6. The client and server can now communicate by writing to or reading from their
sockets.
Client / Server Computing
Server Sockets
To establish a server:
Create a server socket and attach it to a port, which is where the
server listens for connections.
Port numbers range from 0 to 65536, but port numbers 0 to 1024 are
reserved for privileged services. (E.g. Email servers run on 25, Web
server run on port 80).
Code: ServerSocket serverSocket = new ServerSocket(port);
NB: Attempting to create a server socket on a port already in use would cause a
[Link]. (Either handle it or throw it).
After a server socket is created, the server can use the following statement to listen
for connections:,
Code: Socket socket = [Link]();
Methods of the
ServerSocket Class
• socket accept() -- Accepts an incoming connection.
• int getLocalPort() -- Returns the port number on
which the server socket is listening.
• void close() -- Closes the server socket.
Client Sockets
The client issues the following statement to request a connection to a server:
Socket socket = new Socket(serverName, port);
This statement opens a socket so that the client program can communicate
with the server. serverName is the server’s Internet host name or IP address.
The following statement creates a socket on the client machine to connect
to the host [Link] at port 8000:
Socket socket = new Socket("[Link]", 8000); //OR
Socket socket = new Socket(“[Link]", 8000);
A program can use the host name localhost or the IP address
[Link] to refer to the machine on which a client is running.
The Socket constructor throws a [Link]
if the host cannot be found.
Basic Steps to Make it All
1.
Happen
Open a socket.
2. Open an input stream and output stream to the socket.
3. Read from and write to the stream.
4. Close the streams.
5. Close the socket
Example: It just creates the
connection
public class MyServer {
public static void main(String[] args) {
try {
ServerSocket srvSkt = new ServerSocket(1122);
[Link](“Waiting for client’s connection request..");
Socket skt = [Link]();
[Link](“Connection Successful!”);
} catch (Exception e) {
[Link](“Connection Problem Occurred!”);
}
}
}
--------------------------------------------------------------------------------------------------------------------------
public class Client {
public static void main(String[] args) {
try {
Socket skt = new Socket("localhost",1122);
[Link](“Connected to server!”);
} catch (Exception e) {
[Link](“Connection Problem Occurred!”);
}
}
}
Chat Example: Server
public class MyServer {
public static void main(String[] args) throws
Exception { Scanner sc = new Scanner([Link]);
ServerSocket srvSkt = new ServerSocket(1122); while (true) {
[Link]("Me: ");
[Link]("Waiting for client.."); msg = [Link]();
Socket skt = [Link](); [Link](msg);
[Link]("Successful!"); [Link]("Client: " +
[Link]());
DataInputStream din = new
}
DataInputStream([Link]());
}
DataOutputStream dout = new }
DataOutputStream(([Link]()));
String msg;
Chat Example: Client
import [Link].*; import [Link]; import [Link];
public class Client {
public static void main(String[] args) throws Exception {
Socket skt = new Socket("localhost", 1122);
[Link]("Connected to server!");
DataInputStream din = new DataInputStream([Link]());
DataOutputStream dout = new DataOutputStream(([Link]()));
String msg; Server Client
Scanner sc = new Scanner([Link]);
while (true) { din din
[Link]("Server: " + [Link]());
[Link]("Me: ");
msg = [Link]();
[Link](msg); dout dout
}
}
}
Assignment 3 ?%
• Create a client/server application that allows to chat using GUI.