0% found this document useful (0 votes)
3 views

Networking

The document provides an overview of networking basics, focusing on the TCP/IP stack, including the application, transport, network, and link layers. It explains the differences between TCP and UDP protocols, the concept of ports, and how to implement socket communication in Java. Additionally, it details the creation of server and client applications using Java's networking classes, including handling exceptions and multithreading for concurrent client servicing.

Uploaded by

Bansi shah
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Networking

The document provides an overview of networking basics, focusing on the TCP/IP stack, including the application, transport, network, and link layers. It explains the differences between TCP and UDP protocols, the concept of ports, and how to implement socket communication in Java. Additionally, it details the creation of server and client applications using Java's networking classes, including handling exceptions and multithreading for concurrent client servicing.

Uploaded by

Bansi shah
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 33

Networking

Networking Basics

• Applications Layer • TCP/IP Stack


– Standard apps
• HTTP
• FTP
• Telnet Application
– User apps (http,ftp,telnet,…)
• Transport Layer
– TCP Transport
– UDP (TCP, UDP,..)
– Programming Interface:
• Sockets Network
• Network Layer (IP,..)
– IP
Link
• Link Layer (device driver,..)
– Device drivers

2
Networking Basics
• TCP (Transport Control Protocol) is a connection-oriented protocol
that provides a reliable flow of data between two computers.
• TCP provides a point-to-point channel for applications that require
reliable communications
• Reliable
• Error and flow control.
• Order guaranteed.
• Delivery guaranteed.
• Example applications:
– HTTP
– FTP
– Telnet

3
Networking Basics
• UDP (User Datagram Protocol) is a protocol that sends
independent packets of data, called datagrams, from one
computer to another with no guarantees about arrival.
• Not reliable
• Losses, duplicates…
• Order of arrival not guaranteed.
• Delivery not guaranteed.
• Example applications:
– Clock server
– Ping

4
Understanding Ports
• One machine one
address, but several P
o TCP
applications: server
r Client
t
• How to distinguish
different connections?
• A Port is a 16-bit
number that identifies
an application in a app app app app

remote machine.
port port port port

TCP or UDP
Packet
Data port# data
5
Understanding Ports
• Port is represented by a positive (16-bit) integer value
• Some ports have been reserved to support common/well
known services:
– ftp 21/tcp
– telnet 23/tcp
– smtp 25/tcp
– login 513/tcp
– HTTP 80
• User level process/services generally use port number value >=
1024
• Use ports 1024-65,535 for your own applications
• Administrator privileges are required for working with ports in
the range 0-1023.
6
Sockets
• Sockets provide an interface for programming networks at the
transport layer.
• Network communication using Sockets is very much similar to
performing file I/O
– In fact, socket handle is treated like file handle.
– The streams used in file I/O operation are also applicable to socket-
based I/O
• Socket-based communication is programming language
independent.
– That means, a socket program written in Java language can also
communicate to a program written in Java or non-Java socket
program.

7
Socket Communication
• A server (program) runs on a specific
computer and has a socket that is bound to a
specific port. The server waits and listens to
the socket for a client to make a connection
request.

Socket client = new Socket("133.0.0.1", 1234);


Connection request
port

server
Client

8
Socket Communication
• If everything goes well, the server accepts the connection.
Upon acceptance, the server gets a new socket bounds to a
different port. It needs a new socket (consequently a different
port number) so that it can continue to listen to the original
socket for connection requests while serving the connected
client.
port

server

port
Client
port Connection

9
Sockets and Java Socket Classes
• 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 so that the
TCP layer can identify the application that data
destined to be sent.
• Java’s .net package provides two classes:
– Socket – for implementing a client
– ServerSocket – for implementing a server

10
Java Sockets
Server ServerSocket(1234)

Output/write stream Client

Input/read stream

Socket(“128.250.25.158”, 1234)
It can be host_name like “mandroo.cs.mu.oz.au” 11
Java Networking Classes

IP addresses
InetAddress
Packets
DatagramPacket
Sockets
Socket
ServerSocket
DatagramSocket
URLs
URL
InetAddress Class
•Represents an IP address
•Can convert domain name to IP address
•Performs DNS lookup
•Getting an InetAddress object
• getLocalHost()
• getByName(String host)
• getByAddress(byte[] addr)
You can’t create InetAddress objects by invoking the InetAddress constructor
Instead, invoke static methods of the InetAddress class.These methods
return either a Inet4Address or a Inet6Address both of which extend
InetAddress

• Other imp methods


• String getHostAddress()
Returns the IP address string in textual presentation. String
getHostName()
Gets the host name for this IP address.
import java.net.*;
class inetaddtest
{
public static void main(String args[])
{
try
{
InetAddress add=InetAddress.getLocalHost();
System.out.println("Add :"+add);
System.out.println("computer Name\t" +add.getHostName());
System.out.println("IP Address of machine \t
"+add.getHostAddress());

}
catch(Exception e){}
}
}
How to program with sockets:

• Server side
• Create a server socket and bind it to a “well-known” port.
• Listen for incoming clients.
• Upon acceptance, create a normal socket for each client.
• Get output and input streams from the socket.
• Communicate with the client through the streams from the socket.
• Close the socket.
• Client side
• Create a normal socket in any available local port.
• Connect it to the remote server (in Java, this is done at creation).
• Communicate with the server through streams from the socket.
• Close the socket.
The ServerSocket Class

Provides the basic functionalities of a server


● Has four constructors
1.- Import network, input/output and application dependent classes .
import java.net.*;
import java.io.*;
public class EchoingServer {
public static void main(String [] args) {
ServerSocket server = null;
Socket client;
try {
server = new ServerSocket(1234); //2.- Create a server socket in a “well-//known”
port. 1234 is an unused port number
} catch (IOException ie) {
System.out.println("Cannot open socket.");
System.exit(1);
}
//continued...
while(true) {
{
client = server.accept(); // 3.- Create a new client socket upon //acceptance.
OutputStream clientOut = client.getOutputStream();
PrintWriter pw = new PrintWriter(clientOut, true);
InputStream clientIn = client.getInputStream(); // 4.- Get a stream from the socket
BufferedReader br = new BufferedReader(new InputStreamReader(clientIn));
pw.println(br.readLine());//send answer to the client.

} catch (IOException ie) {}


}
}
}
The Socket Class
● Implements a client socket
● Has eight constructors
– Two of which are already deprecated
import java.io.*;
import java.net.*;
public class MyClient {
public static void main(String args[]) {
try {
/* Socket client = new Socket("133.0.0.1",
1234); */
Socket client =
new Socket(InetAddress.getLocalHost(), 1234);
//Create a client socket connected to the right server and port
InputStream clientIn = client.getInputStream(); //get a input
stream from socket for receiving data from server
OutputStream clientOut =client.getOutputStream(); //get a
output stream from socket for sending data to server
PrintWriter pw = new PrintWriter(clientOut, true);
BufferedReader br = new BufferedReader(new
InputStreamReader(clientIn));
BufferedReader stdIn = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Type a message for the server: ");
pw.println(stdIn.readLine());
System.out.println("Server message: ");
System.out.println(br.readLine());
pw.close();
br.close();
client.close();
} catch (ConnectException ce) {
System.out.println("Cannot connect to the server.");
} catch (IOException ie) {
System.out.println("I/O Error.");
}
}
}
Implementing a Server
1. Open the Server Socket:
ServerSocket server;
DataOutputStream os;
DataInputStream is;
server = new ServerSocket( PORT );
2. Wait for the Client Request:
Socket client = server.accept();
3. Create I/O streams for communicating to the client
is = new DataInputStream( client.getInputStream() );
os = new DataOutputStream( client.getOutputStream() );
4. Perform communication with client
Receive from client: String line = is.readLine();
Send to client: os.writeBytes("Hello\n");
5. Close sockets: client.close();
For multithreaded server:
while(true) {
i. wait for client requests (step 2 above)
ii. create a thread with “client” socket as parameter (the thread creates streams (as in step (3)
and does communication as stated in (4). Remove thread once service is provided.
}

25
Implementing a Client
1. Create a Socket Object:
client = new Socket( server, port_id );
2. Create I/O streams for communicating with the server.
is = new DataInputStream(client.getInputStream() );
os = new DataOutputStream( client.getOutputStream() );
3. Perform I/O or communication with the server:
– Receive data from the server:
String line = is.readLine();
– Send data to the server:
os.writeBytes("Hello\n");
4. Close the socket when done:
client.close();

26
A simple server (simplified code)
// SimpleServer.java: a simple server program
import java.net.*;
import java.io.*;
public class SimpleServer {
public static void main(String args[]) throws IOException {
// Register service on port 1234
ServerSocket s = new ServerSocket(1234);
Socket s1=s.accept(); // Wait and accept a connection
// Get a communication stream associated with the socket
OutputStream s1out = s1.getOutputStream();
DataOutputStream dos = new DataOutputStream (s1out);
// Send a string!
dos.writeUTF("Hi there");
// Close the connection, but not the server socket
dos.close();
s1out.close();
s1.close();
}
}

27
A simple client (simplified code)
// SimpleClient.java: a simple client program
import java.net.*;
import java.io.*;
public class SimpleClient {
public static void main(String args[]) throws IOException {
// Open your connection to a server, at port 1234
Socket s1 = new Socket("mundroo.cs.mu.oz.au",1234);
// Get an input file handle from the socket and read the input
InputStream s1In = s1.getInputStream();
DataInputStream dis = new DataInputStream(s1In);
String st = new String (dis.readUTF());
System.out.println(st);
// When done, just close the connection and exit
dis.close();
s1In.close();
s1.close();
}
}

28
Run
• Run Server on mundroo.cs.mu.oz.au
– [raj@mundroo] java SimpleServer &

• Run Client on any machine (including mundroo):


– [raj@mundroo] java SimpleClient
Hi there

• If you run client when server is not up:


– [raj@mundroo] sockets [1:147] java SimpleClient
Exception in thread "main" java.net.ConnectException: Connection refused
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:320)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:133)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:120)
at java.net.Socket.<init>(Socket.java:273)
at java.net.Socket.<init>(Socket.java:100)
at SimpleClient.main(SimpleClient.java:6)

29
Socket Exceptions
try {
Socket client = new Socket(host, port);
handleConnection(client);
}
catch(UnknownHostException uhe)
{ System.out.println("Unknown host: " + host);
uhe.printStackTrace();
}
catch(IOException ioe) {
System.out.println("IOException: " + ioe); ioe.printStackTrace();
}

30
ServerSocket & Exceptions
• public ServerSocket(int port) throws IOException
– Creates a server socket on a specified port.
– A port of 0 creates a socket on any free port. You can use getLocalPort
() to identify the (assigned) port on which this socket is listening.
– The maximum queue length for incoming connection indications (a
request to connect) is set to 50. If a connection indication arrives
when the queue is full, the connection is refused.
• Throws:
– IOException - if an I/O error occurs when opening the socket.
– SecurityException - if a security manager exists and its checkListen
method doesn't allow the operation.

31
Server in Loop: Always up
// SimpleServerLoop.java: a simple server program that runs forever in a single thead
import java.net.*;
import java.io.*;
public class SimpleServerLoop {
public static void main(String args[]) throws IOException {
// Register service on port 1234
ServerSocket s = new ServerSocket(1234);
while(true)
{
Socket s1=s.accept(); // Wait and accept a connection
// Get a communication stream associated with the socket
OutputStream s1out = s1.getOutputStream();
DataOutputStream dos = new DataOutputStream (s1out);
// Send a string!
dos.writeUTF("Hi there");
// Close the connection, but not the server socket
dos.close();
s1out.close();
s1.close();
}
}
}

32
Multithreaded Server: For Serving Multiple
Clients Concurrently

Client 1 Process Server Process

Server
Threads
Internet

Client 2
Process

33

You might also like