0% found this document useful (0 votes)
4 views29 pages

Networking (Socket Programming)

The document provides an overview of network programming, specifically focusing on socket programming using Java's java.net package. It explains the concepts of TCP and UDP protocols, the role of sockets in client/server communication, and outlines the steps for creating simple server and client programs. Additionally, it details the ServerSocket and Socket class methods necessary for establishing and managing connections.

Uploaded by

betukartik
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views29 pages

Networking (Socket Programming)

The document provides an overview of network programming, specifically focusing on socket programming using Java's java.net package. It explains the concepts of TCP and UDP protocols, the role of sockets in client/server communication, and outlines the steps for creating simple server and client programs. Additionally, it details the ServerSocket and Socket class methods necessary for establishing and managing connections.

Uploaded by

betukartik
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Networking (Socket

Programming)

The term network programming refers to


writing programs that execute across multiple
devices (computers), in which the devices are
all connected to each other using a network.

1
Networking (Socket
Programming)
• The [Link] package of the J2SE APIs contains a
collection of classes and interfaces that provide the low-
level communication details, allowing you to write
programs that focus on solving the problem at hand.
• The [Link] package provides support for the two
common network protocols:
1. TCP: TCP stands for Transmission Control Protocol,
which allows for reliable communication between two
applications. TCP is typically used over the Internet
Protocol, which is referred to as TCP/IP.
2. UDP: UDP stands for User Datagram Protocol, a
connection-less protocol that allows for packets of data
to be transmitted between applications.

2
SOCKET

3
The conceptual model of the socket
API
P ro c ess A P ro c ess B

a socket
4
The Socket API
• A socket API provides a programming
construct termed a socket.
• A process wishing to communicate with
another process must create an instance,
or instantiate, such a construct.
• The two processes then issue operations
provided by the API to send and receive
data.
5
What is socket
• A network socket is an endpoint of an inter-
process communication flow across a computer
network
• A socket is a communication mechanism that allows
client/server systems to be developed either locally, on
a single machine, or across networks.
• Sockets are created and used differently from pipes
because they make a clear distinction between client
and server.
• The socket mechanism can implement multiple clients
attached to a single server.
6
Socket types
• There are several Internet socket types available:
• Datagram sockets, also known as connectionless sockets, which
use User Datagram Protocol (UDP)
• Stream sockets, also known as connection-oriented sockets, which
use Transmission Control Protocol (TCP) or Stream Control
Transmission Protocol (SCTP).
• Raw sockets (or Raw IP sockets), typically available in routers and
other network equipment. Here the transport layer is bypassed, and the
packet headers are not stripped off, but are accessible to the
application.
• Application examples are Internet Control Message Protocol (ICMP,
best known for the Ping suboperation), Internet Group Management
Protocol(IGMP), and Open Shortest Path First (OSPF)
7
Socket vs Port

• A port is a software address on a computer on the


network--for instance, the News server is a piece of
software that is normally addressed through port 119, the
POP server through port 110, the SMTP server through
port 25, and so on.
• A socket is a communication path to a port.
• When you want your program to communicate over the
network, you have given it a way of addressing the port and
this is done by creating a socket and attaching it to the port.
• Basically, socket = IP + ports Sockets provide access to
the port+ip

8
ICANN Ranges
• ICANN has divided port numbers into three ranges well-
known , registered, and dynamic

• Well-known ports– ports ranging from 0 to 1023 are assigned and


controlled by ICANN
• Registered ports– ports ranging from 1024 to 49151 are not assigned
and controlled by ICANN. They can only be registered with ICANN to
prevent duplication
• Dynamic ports– ports ranging from 49152 to 65535 are neither controlled
nor registered, is used as temporaray or private port numbers

9
Socket Programming via TCP
• Sockets provide the communication mechanism between
two computers using TCP.
• A client program creates a socket on its end of the
communication and attempts to connect that socket to a
server.
• When the connection is made, the server creates a
socket object on its end of the communication.
• The client and server can now communicate by writing to
and reading from the socket.
• The [Link] class represents a socket, and the
[Link] class provides a mechanism for
the server program to listen for clients and establish
connections with them.

10
Socket Programming via TCP
• The following steps occur when establishing a TCP connection
between two computers using sockets:
1. The server instantiates a ServerSocket object, denoting which port
number communication is to occur on.
2. The server invokes the accept() method of the ServerSocket class.
This method waits until a client connects to the server on the given
port.
3. After the server is waiting, a client instantiates a Socket object,
specifying 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.

11
Socket Programming via TCP
• 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.

12
ServerSocket Class Methods
• The [Link] class is used
by server applications to obtain a port and
listen for client requests
• There are four constructors:

13
ServerSocket Class constructors
1. public ServerSocket(int port) throws IOException
Attempts to create a server socket bound to the specified port. An
exception occurs if the port is already bound by another application.
2. public ServerSocket(int port, int backlog) throws IOException
Similar to the previous constructor, the backlog parameter specifies
how many incoming clients to store in a wait queue.
3. public ServerSocket(int port, int backlog, InetAddress address)
throws IOException
Similar to the previous constructor, the InetAddress parameter specifies
the local IP address to bind to. The InetAddress is used for servers that
may have multiple IP addresses, allowing the server to specify which of
its IP addresses to accept client requests on
4. public ServerSocket() throws IOException
Creates an unbound server socket. When using this constructor, use
the bind() method when you are ready to bind the server socket
• If the ServerSocket constructor does not throw an exception, it means
that your application has successfully bound to the specified port and is
ready for client requests.
14
Common methods of the
ServerSocket class
• public int getLocalPort()

• Returns the port that the server socket is listening on.


This method is useful if you passed in 0 as the port
number in a constructor and let the server find a port for
you.
• public Socket accept() throws IOException

• Waits for an incoming client. This method blocks until


either a client connects to the server on the specified
port or the socket times out, assuming that the time-out
value has been set using the setSoTimeout() method.
Otherwise, this method blocks indefinitely

15
Common methods of the
ServerSocket class
• public void setSoTimeout(int timeout)

• Sets the time-out value for how long the server socket
waits for a client during the accept().
• public void bind(SocketAddress host, int backlog)

• Binds the socket to the specified server and port in the


SocketAddress object. Use this method if you
instantiated the ServerSocket using the no-argument
constructor.

16
Common methods of the
ServerSocket class
• When the ServerSocket invokes accept(), the
method does not return until a client connects.
• After a client does connect, the ServerSocket
creates a new Socket on an unspecified port and
returns a reference to this new Socket.
• A TCP connection now exists between the client
and server, and communication can begin.

17
Socket Class Methods
• The [Link] class represents the socket that
both the client and server use to communicate with each
other.
• The client obtains a Socket object by instantiating one,
whereas the server obtains a Socket object from the
return value of the accept() method.
• The Socket class has five constructors that a client uses
to connect to a server:

18
Socket Class Constructor
• public Socket(String host, int port) throws
UnknownHostException, IOException.

• This method attempts to connect to the specified server at the


specified port. If this constructor does not throw an exception, the
connection is successful and the client is connected to the server.
• public Socket(InetAddress host, int port) throws IOException

• This method is identical to the previous constructor, except that the


host is denoted by an InetAddress object.
• public Socket(String host, int port, InetAddress localAddress,
int localPort) throws IOException.

• Connects to the specified host and port, creating a socket on the


local host at the specified address and port.

19
Socket Class Constructor
• public Socket(InetAddress host, int port, InetAddress
localAddress, int localPort) throws IOException.

• This method is identical to the previous constructor, except that the


host is denoted by an InetAddress object instead of a String
• public Socket()

• Creates an unconnected socket. Use the connect() method to


connect this socket to a server.

• When the Socket constructor returns, it does not simply instantiate a


Socket object but it actually attempts to connect to the specified
server and port.

20
Socket class Methods
• public void connect(SocketAddress host, int timeout)
throws IOException

• This method connects the socket to the specified host.


This method is needed only when you instantiated the
Socket using the no-argument constructor.
• public InetAddress getInetAddress()

• This method returns the address of the other computer


that this socket is connected to.
• public int getPort()

• Returns the port the socket is bound to on the remote


machine.
21
Socket class Methods
• public int getLocalPort()

• Returns the port the socket is bound to on the local


machine.
• public SocketAddress getRemoteSocketAddress()

• Returns the address of the remote socket.


• public InputStream getInputStream() throws
IOException

• Returns the input stream of the socket. The input stream


is connected to the output stream of the remote socket.
22
InetAddress Class Methods:

This class represents an Internet


Protocol (IP) address.

23
InetAddress Class Methods
S
Methods with Description
N
static InetAddress getByAddress(byte[] addr)
1
Returns an InetAddress object given the raw IP address .
static InetAddress getByAddress(String host, byte[] addr)
2
Create an InetAddress based on the provided host name and IP address.
static InetAddress getByName(String host)
3
Determines the IP address of a host, given the host's name.
String getHostAddress()
4
Returns the IP address string in textual presentation.
String getHostName()
5
Gets the host name for this IP address.
static InetAddress InetAddress getLocalHost()
6
Returns the local host.
String toString()
7
Converts this IP address to a String. 24
The steps for creating a simple
server program in TCP
1. Open the Server Socket:
ServerSocket server = new ServerSocket( PORT );
2. Wait for the Client Request:
Socket client = [Link]();
3. Create I/O streams for communicating to the client
DataInputStream is = new
DataInputStream([Link]());
DataOutputStream os = new
DataOutputStream([Link]());
4. Perform communication with client
Receive from client: String line = [Link]();
Send to client: [Link](“Hello\n”);
5. Close socket:

25
The steps for creating a simple
server program in TCP
• OutputStream getOutputStream() //
used for writing to Socket
• InputStream getInputStream() // used for
reading from Socket

26
// [Link]: A simple server program.
import [Link].*;
import [Link].*;
public class SimpleServer {
public static void main(String args[]) throws IOException {
// Register service on port 1254
ServerSocket s = new ServerSocket(1254);
Socket s1=[Link](); // Wait and accept a connection
// Get a communication stream associated with the socket
OutputStream s1out = [Link]();
DataOutputStream dos = new DataOutputStream (s1out);
// Send a string!
[Link](“Hi there”);
// Close the connection, but not the server socket
[Link]();
[Link]();
[Link]();
}
}
27
The steps for creating a simple
client program in TCP
1. Create a Socket Object:
Socket client = new Socket(server, port_id);
2. Create I/O streams for communicating with the server.
is = new DataInputStream([Link]());
os = new DataOutputStream([Link]());
3. Perform I/O or communication with the server:
Receive data from the server: String line = [Link]();
Send data to the server: [Link](“Hello\n”);
4. Close the socket when done:
[Link]();

28
// [Link]: A simple client program.
import [Link].*;
import [Link].*;
public class SimpleClient {
public static void main(String args[]) throws IOException {
// Open your connection to a server, at port 1254
Socket s1 = new Socket(“localhost”,1254);
// Get an input file handle from the socket and read the input
InputStream s1In = [Link]();
DataInputStream dis = new DataInputStream(s1In);
String st = new String ([Link]());
[Link](st);
// When done, just close the connection and exit
[Link]();
[Link]();
[Link]();
}
}
29

You might also like