• No results found

Network Programming in java

N/A
N/A
Protected

Academic year: 2020

Share "Network Programming in java"

Copied!
74
0
0

Loading.... (view fulltext now)

Full text

(1)

Network Programming in java

Lecture

(2)

Socket concepts

A B C X Y Z Mayur villa nirwan villa 2

(3)

Socket concepts

A B C X Y Z Mayur villa nirwan villa I have to write letter to Mr. X. Nirwan Villa 3

(4)

Socket concepts

A B C X Y Z Mayur villa nirwan villa I have to write letter to Mr. X.

?

?

?

4

(5)

Socket concepts

A B C X Y Z Mayur villa nirwan villa I have to write letter to Mr. X. Mr. X Nirwan Villa 5

(6)

Socket concepts

A B C X Y Z Mayur villa nirwan villa I have to write letter to Mr. X. I got a letter. 6

(7)

Computer networks

210.23.34.21 118.123.34.11 118.123.34.11

?

?

?

7

(8)

Solution

Port Number

(9)

Computer networks

210.23.34.21 118.123.34.11 118.123.34.11, 21 102 678 21 9

(10)

Socket

IP address + Port Number

(11)

Well know port

Service Port Telnet 23 SMTP 25 DNS 53 HTTP 80 HTTPS 443

Apple quick time 458

(12)

What is a socket?

• Socket

– The combination of an IP address and a port number. (RFC 793 ,original TCP specification)

– The name of the Berkeley-derived application programming interfaces (APIs) for applications using TCP/IP protocols.

– Two types

• Stream socket : reliable two-way connected communication streams • Datagram socket

• Socket pair

– Specified the two end points that uniquely identifies each TCP connection in an internet.

– 4-tuple: (client IP address, client port number, server IP address, server port number)

(13)

Host Guest Scenario

Host waiting for guest Receive Guest

Serve them

(14)

Client Server Scenario

Server waiting for client Receive request

Process client request

Request

Response

(15)

Network Application

You need to develop

Server

Client

(16)

Developing Server in java

1. Server program waiting for client request. 2. Client Server exchange information

3. Close the connection

(17)

Socket programming

Tcp/ip

Connection Oriented

Udp/ip

Connection Less

17

(18)

Socket class

• Corresponds to active TCP sockets only!

– Socket(Client)

– socket returned by accept();

• Passive sockets are supported by a different class:

– ServerSocket(Server)

• UDP sockets are supported by

– DatagramSocket

(19)

JAVA TCP Sockets

• java.net.Socket

– Implements client sockets (also called just “sockets”).

– An endpoint for communication between two machines.

– Constructor and Methods

Socket(String host, int port): Creates a stream socket and connects it to the specified port number on the named host.

InputStream getInputStream() OutputStream getOutputStream() close()

• java.net.ServerSocket

– Implements server sockets.

– Waits for requests to come in over the network.

– Performs some operation based on the request.

– Constructor and Methods

ServerSocket(int port)

Socket Accept(): Listens for a connection to be made to this socket and accepts it. This method blocks until a connection is made.

(20)

Socket Programming with TCP

Figure 2.6-1: Processes communicating through TCP sockets

The application developer has the ability to fix a few TCP

(21)

TCP Connection Oriented

Request for connection

Ok connection Data Exchange Connection close request Connection closed 21

(22)

UDP-Connection Less

Data Exchange

(23)

TCP three way handshaking

12350 12349 12348 12347 12346 12345 23123 23122 23121 23120 23119 23118

My data packet sequence start from 1234

SYN

I receiced your sequence number + My data packet sequence start from 23118

SYN + ACK

I have received your sequence number.

ACK

1

2

3

(24)

Creating server in java: Step1

ServerSocket sc=new ServerSocket(<Port Number>);

ServerSocket sc=new ServerSocket(1700);

One server is created.

Port number 1700 will be assigned to this server.

Hint: Can we change this port number

(25)

Creating server in java: Step2

Start Waiting for client

Socket so=so.accept();

(26)

Creating client in java: Step1

Socket so=new Socket(127.0.0.1,1700);

Client making request for connection.

If server running accept() method, then server allow request and

Connection will be established.

Socket so=new Socket(<ip address>,port);

(27)

Sockets for server and client

• Server

– Welcoming socket

• Welcomes some initial contact from a client.

– Connection socket

• Is created at initial contact of client.

• New socket that is dedicated to the particular client.

• Client

– Client socket

• Initiate a TCP connection to the server by creating a socket object. (Three-way handshake)

• Specify the address of the server process, namely, the IP address of the server and the port number of the process.

(28)

Socket functional calls

• socket (): Create a socket

• bind(): bind a socket to a local IP address and port #

• listen(): passively waiting for connections

• connect(): initiating connection to another socket

• accept(): accept a new connection

• Write(): write data to a socket

• Read(): read data from a socket

• sendto(): send a datagram to another UDP socket

• recvfrom(): read a datagram from a UDP socket

(29)

Sockets

(30)

Socket-programming using TCP

TCP service:

reliable byte stream transfer

process TCP with buffers, variables socket controlled by application developer controlled by operating system process TCP with buffers, variables socket

internet

client server socket( ) bind( ) connect( ) socket( ) bind( ) listen( ) accept( ) send( ) recv( ) close( ) close( ) recv( ) send( ) TCP

conn. request

TCP ACK

(31)

Socket programming with TCP

Example client-server app:

• client reads line from standard

input (inFromUser stream) ,

sends to server via socket

(outToServer stream)

• server reads line from socket

• server converts line to

uppercase, sends back to client

• client reads, prints modified

line from socket

(inFromServer stream)

Input stream: sequence of bytes into process output stream: sequence of bytes out of process

Client

process

client TCP socket

(32)

Client/server socket interaction: TCP

wait for incoming connection request Socket conSocket = wc.accept() create socket, port=x, for incoming request: ServerSocket wc = new ServerSocket(x) create socket,

connect to hostid, port=x

Socket clientSocket = new Socket(server ip, port)

close

connectionSocket

read reply from

clientSocket

close

clientSocket

Server (running on hostid) Client

send request using

clientSocket

read request from

connectionSocket write reply to connectionSocket TCP connection setup 32

(33)

33

TCP Client/Server Interaction

Client

1. Create a TCP socket 2. Communicate

3. Close the connection

Server

1. Create a TCP socket 2. Repeatedly:

a. Accept new connection

b. Communicate

c. Close the connection

(34)

34

TCP Client/Server Interaction

Client

1. Create a TCP socket 2. Communicate

3. Close the connection

Server

1. Create a TCP socket 2. Repeatedly:

a. Accept new connection

b. Communicate

c. Close the connection ServerSocket servSock = new ServerSocket(servPort);

(35)

35

TCP Client/Server Interaction

Client

1. Create a TCP socket 2. Communicate

3. Close the connection

Server

1. Create a TCP socket 2. Repeatedly:

a. Accept new connection

b. Communicate

c. Close the connection for (;;) {

(36)

36

TCP Client/Server Interaction

Client

1. Create a TCP socket 2. Communicate

3. Close the connection

Server

1. Create a TCP socket 2. Repeatedly:

a. Accept new connection

b. Communicate

c. Close the connection Server is now blocked waiting for connection from a client

(37)

37

TCP Client/Server Interaction

Client

1. Create a TCP socket 2. Communicate

3. Close the connection

Server

1. Create a TCP socket 2. Repeatedly:

a. Accept new connection

b. Communicate

c. Close the connection Later, a client decides to talk to the server…

(38)

38

TCP Client/Server Interaction

Client

1. Create a TCP socket 2. Communicate

3. Close the connection

Server

1. Create a TCP socket 2. Repeatedly:

a. Accept new connection

b. Communicate

c. Close the connection Socket socket = new Socket(server, servPort);

(39)

39

TCP Client/Server Interaction

Client

1. Create a TCP socket 2. Communicate

3. Close the connection

Server

1. Create a TCP socket 2. Repeatedly:

a. Accept new connection

b. Communicate

c. Close the connection OutputStream out = socket.getOutputStream();

(40)

40

TCP Client/Server Interaction

Client

1. Create a TCP socket 2. Communicate

3. Close the connection

Server

1. Create a TCP socket 2. Repeatedly:

a. Accept new connection

b. Communicate

c. Close the connection Socket clntSock = servSock.accept();

(41)

41

TCP Client/Server Interaction

Client

1. Create a TCP socket 2. Communicate

3. Close the connection

Server

1. Create a TCP socket 2. Repeatedly:

a. Accept new connection

b. Communicate

c. Close the connection InputStream in = clntSock.getInputStream();

(42)

42

TCP Client/Server Interaction

Client 1. Create a TCP socket 2. Establish connection 3. Communicate

4. Close the connection

Server

1. Create a TCP socket 2. Bind socket to a port 3. Set socket to listen 4. Repeatedly:

a. Accept new connection

b. Communicate

c. Close the connection

(43)

Connection-Client

import java.io.*;

import java.net.*;

class Client1

{

public static void main(String g[]) throws IOException

{

Socket s1=new Socket("localhost",9090);

System.out.println("connect");

}

}

Importing package required for input/output and socket programming

(44)

Server

import java.io.*;

import java.net.*;

public class Server1

{

public static void main(String g[]) throws IOException

{

ServerSocket ss=new ServerSocket(9090);

Socket s=ss.accept();

System.out.println("Connect");

}

}

Importing package required for input/output and socket programming

Start server Start waiting for client

(45)

How to exchange information?

Streams

Get a stream from socket and perform read/write operation on that stream.

sc.getOutputStream

();

sc.getInputStream

();

(46)

Reading from keyboard. Uses an input stream like

BufferedReader connected to System.in.

Sending data to the other system what is read from keyboard. Uses an

output stream like PrintWriter connected to getOutputStream() method of

Socket.

Receiving data from the other system. Uses an input stream like

(47)

Server

import java.io.*; import java.net.*

public class myServer {

public static void main(String[] args) throws IOException { ServerSocket listener = new ServerSocket(9090);

try {

Socket socket = listener.accept(); try {

PrintWriter out = new PrintWriter(socket.getOutputStream(), true); out.println(“Hello this is server”);

} catch(Exception e) { System.out.println(e); } } catch(Exception e) { System.out.println(e); } } }

DataOutputStream dos=new DataOutputStream(socket.getOutputStream()); dos.writeUTF(“Hello this is sever”);

Importing package required for input/output and socket programming

Start server Start waiting for client request.

(48)

Client

import java.io.*; import java.net.*; class myClient {

public static void main(String[] args) throws IOException {

Socket s = new Socket(“127.0.0.1”, 9090);

DataInputStream dis=new DataInputStream(s.getInputStream()); String answer=dis.readUTF();

System.out.println(“msg from server”+answer); System.exit(0);

} } }

(49)

49

Example: Java client (TCP)

import java.io.*;

import java.net.*; class TCPClient {

public static void main(String argv[]) throws Exception {

String sentence;

String modifiedSentence;

BufferedReader inFromUser =

new BufferedReader(new InputStreamReader(System.in)); Socket clientSocket = new Socket("hostname", 6789);

DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream()); Create input stream Create client socket, connect to server Create output stream attached to socket

(50)

50

Example: Java client (TCP), cont.

BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); sentence = inFromUser.readLine(); outToServer.writeBytes(sentence + '\n'); modifiedSentence = inFromServer.readLine();

System.out.println("FROM SERVER: " + modifiedSentence);

clientSocket.close(); } } Create input stream attached to socket Send line to server Read line from server

(51)

51

Example: Java server (TCP)

import java.io.*; import java.net.*;

class TCPServer {

public static void main(String argv[]) throws Exception {

String clientSentence;

String capitalizedSentence;

ServerSocket welcomeSocket = new ServerSocket(6789);

while(true) {

Socket connectionSocket = welcomeSocket.accept();

BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream())); Create welcoming socket at port 6789 Wait, on welcoming

socket for contact by client Create input stream, attached

(52)

52

Example: Java server (TCP), cont

DataOutputStream outToClient =

new DataOutputStream(connectionSocket.getOutputStream());

clientSentence = inFromClient.readLine(); capitalizedSentence = clientSentence.toUpperCase() + '\n'; outToClient.writeBytes(capitalizedSentence); } } } Read in line from socket Create output stream, attached to socket

Write out line to socket

End of while loop, loop back and wait for another client connection

(53)

Problem

Communication can be seen by any person on

network.

Not secure

Can’t be used for sensitive information

exchange.

(54)

Port Scanner

Check for port range 0-65535. Is there any

port is open( any network application is

running on target machine or not)

(55)

Port scanner

import java.io.*;

import java.net.*;

class myClient

{

public static void main(String[] args) throws IOException {

try{

Socket s = new Socket(“128.10.100.2”, 6588);

System.out.println(Port is open”);

}

catch(Exception e)

{ System.out.println(“Port is not open”); }

}

}

(56)

Efficiency

Program only check whether 6588 port is

open or not.

Genarally we want to see how many ports are

open.

(57)

Port scanner

import java.io.*;

import java.net.*;

class myClient

{

public static void main(String[] args) throws IOException {

try{

Socket s = new Socket(“128.10.100.2”, 6588 );

System.out.println(Port is open”);

}

catch(Exception e)

{ System.out.println(“Port is not open”); }

}

}

For(int i=0;i<65535;i++) {

} i 57

(58)

URL

import java.io.*;

import java.net.*;

public class URLDemo{

public static void main(String[] args){

try{

URL url=new URL("http://www.gmail.com");

System.out.println("Protocol: "+url.getProtocol());

System.out.println("Host Name: "+url.getHost());

System.out.println("Port Number: "+url.getPort());

System.out.println("File Name: "+url.getFile());

}catch(Exception e){System.out.println(e);}

}

(59)

IntelAddress

import java.io.*;

import java.net.*;

public class InetDemo{

public static void main(String[] args){

try{

InetAddress

ip=InetAddress.getByName("www.gmail.com");

System.out.println("Host Name: "+ip.getHostName());

System.out.println("IP Address:

"+ip.getHostAddress());

}catch(Exception e){System.out.println(e);}

}

(60)

Socket Programming with UDP

• UDP

– Connectionless and unreliable service.

– There isn’t an initial handshaking phase.

– Doesn’t have a pipe.

transmitted data may be received out of order, or lost

• Socket Programming with UDP

– No need for a welcoming socket.

– No streams are attached to the sockets.

– the sending hosts creates “packets” by attaching the

IP destination address and port number to each batch

of bytes.

– The receiving process must unravel to received

packet to obtain the packet’s information bytes.

(61)

Client/server socket interaction: UDP

close

clientSocket

Server (running on hostid)

read reply from

clientSocket

create socket,

clientSocket = DatagramSocket()

Client

Create, address (hostid, port=x, send datagram request

using clientSocket create socket, port=x, for incoming request: serverSocket = DatagramSocket()

read request from

serverSocket write reply to serverSocket specifying client host address, port umber

(62)

Example: Java client (UDP)

Output: sends packet (TCP sent “byte stream”) Input: receives packet (TCP received “byte stream”)

Client

process

client UDP socket

(63)

JAVA UDP Sockets

• In Package java.net

– java.net.DatagramSocket

• A socket for sending and receiving datagram

packets.

• Constructor and Methods

– DatagramSocket(int port): Constructs a datagram socket

and binds it to the specified port on the local host

machine.

– void receive( DatagramPacket p)

– void send( DatagramPacket p)

– void close()

(64)

UDPClient.java

import java.io.*;

import java.net.*;

class UDPClient {

public static void main(String args[]) throws Exception

{

BufferedReader inFromUser =

new BufferedReader(new InputStreamReader(System.in));

DatagramSocket clientSocket = new DatagramSocket();

InetAddress IPAddress =

InetAddress.getByName(“localhost");

byte[] sendData = new byte[1024];

byte[] receiveData = new byte[1024];

String sentence = inFromUser.readLine();

(65)

UDPClient.java

DatagramPacket sendPacket =

new DatagramPacket(sendData, sendData.length,

IPAddress, 9876);

clientSocket.send(sendPacket);

DatagramPacket receivePacket =

new DatagramPacket(receiveData, receiveData.length);

clientSocket.receive(receivePacket);

String modifiedSentence =

new String(receivePacket.getData());

System.out.println("FROM SERVER:" + modifiedSentence);

clientSocket.close();

}

}

(66)

UDPServer.java

import java.io.*;

import java.net.*;

class UDPServer {

public static void main(String args[]) throws Exception

{

DatagramSocket serverSocket = new

DatagramSocket(9876);

byte[] receiveData = new byte[1024];

byte[] sendData = new byte[1024];

while(true)

{

DatagramPacket receivePacket =

new DatagramPacket(receiveData, receiveData.length);

serverSocket.receive(receivePacket);

(67)

UDPServer.java

InetAddress IPAddress = receivePacket.getAddress();

int port = receivePacket.getPort();

String capitalizedSentence = sentence.toUpperCase();

sendData = capitalizedSentence.getBytes();

DatagramPacket sendPacket =

new DatagramPacket(sendData, sendData.length, IPAddress, port);

serverSocket.send(sendPacket);

}

}

}

(68)

Multithreading server

1. Create server (using ServerSocket class)

2. Start listening (calling accept method)

3. When a client request received, create a

new thread and in that thread pass socket

object.

4.Put all these three steps in a infinite loop.

(69)

Multithreading server

While(true)

{

ServerSocket ss=new ServerSocket(9999);

Socket so= ss.accept();

ClientHandler ch=new ClientHandler(so);

Thread th=new Thread(ch);

th.start();

}

(70)

Execution of chat server

C:/> java chatserver This is server 1.1 This is client 1.1

This server is not multithreading server Make this multithreading that is better

C:/> java chatclient This is server 1.1 This is client 1.1

This server is not multithreading server Make this multithreading that is better

Server cmd Client cmd

(71)

Chat Server

Chat Client

Create serversocket class object to make server. Call accept method

Make object of input and output stream.

Create socket class object. Make object of input and output stream.

Read from input stream and print.

Read from input stream and print it.

Read from user a string Write that string to output stream.

Read from user a string. Write that string to socket.

(72)

Creating Simple Web Server

www.google.com

Get / http1.1

Host:www.google.com

Accept: image/gif, image/jpeg Accept-language: En

User-Agent: Mozilla/4.0 Connection:keep-Alive

1

(73)

Creating Simple Web Server

www.google.com HTTP/1.1 200 OK Server: server_name Content-length:3001 Content-Type: text/html <html><body> this is demo</body><html> 2 73

(74)

Building a Simple Web Server

• Handles only one HTTP request

• Accepts and parses the HTTP request

• Gets the required file from the server’s file

system.

• Creates an HTTP response message

consisting of the requested file preceded

by header lines

Figure

Figure 2.6-1: Processes communicating through TCP sockets
Figure 2.6-2: Client socket, welcoming socket and connection socket

References

Related documents

Hipped roof, covered in red plain clay tiles, with red brick construction to walls and sandstone plinth, and brick dentil course to eaves. Small diamond-shaped aeration

internal server firewall client SYN SYN SYN+ACK ACK SYN+ACK ACK SYN data data Application Layer Socket Layer TCP/IP Layer NIC driver NIC Application Layer Socket Layer TCP/IP Layer

Understanding the relations between our energy consumption and the global climate change is highly under-emphasized in educational plans (curricula) in most countries. Bringing

Lawrence. Various categories of companies were then eliminated as being outside the field of interest, such as those in the retail trades, all eating establishments, and all

calories. It’s getting your exercise and nutrition working together synergistically at the right times based on your goals. For example, performing bursting or HIIT workouts on

public Socket(String host, int port, InetAddress localAddress, int localPort) throws IOException5. public Socket(InetAddress address, int port, InetAddress localAddress, int

Create input stream Create client socket, connect to server Create output stream attached to socket.. Network

TCP Overview Machine A Machine B Processus client Processus serveur Socket d'écoute 2a.- connect 1a.- socket 1b.- socket 2b.- bind 3b.- listen 4b.- accept Socket de