• No results found

Network/Socket Programming in Java. Rajkumar Buyya

N/A
N/A
Protected

Academic year: 2021

Share "Network/Socket Programming in Java. Rajkumar Buyya"

Copied!
39
0
0

Full text

(1)

Network/Socket Programming

in Java

Rajkumar Buyya

(2)

Network

Request

Result

a client, a server, and network

Client

Server

Client machine

Server machine

Elements of C-S Computing

(3)

java.net

n

Used to manage:

c

URL streams

c

Client/server sockets

c

Datagrams

(4)

4

Part III - Networking

ServerSocket(1234)

Socket(“128.250.25.158”, 1234)

Output/write stream

Input/read stream

Server_name: “manjira.cs.mu.oz.au”

(5)

Server side Socket Operations

1. Open Server Socket:

ServerSocket server;

DataOutputStream os;

DataInputStream is;

server = new ServerSocket( PORT );

2. Wait for Client Request:

Socket client = server.accept();

3. Create I/O streams for communicating to clients

is = new DataInputStream( client.getInputStream() );

os = new DataOutputStream( client.getOutputStream() );

4. Perform communication with client

Receiive from client: String line = is.readLine();

Send to client: os.writeBytes("Hello\n");

5. Close sockets: client.close();

For multithreade 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.

}

(6)

Client side Socket Operations

1. Get connection to server:

client = new Socket( server, port_id );

2. Create I/O streams for communicating to clients

is = new DataInputStream( client.getInputStream() );

os = new DataOutputStream( client.getOutputStream() );

3. Perform communication with client

Receiive from client: String line = is.readLine();

Send to client: os.writeBytes("Hello\n");

4. Close sockets: client.close();

(7)

7

A simple server (simplified code)

import java.net.*;

import java.io.*;

public class ASimpleServer {

public static void main(String args[]) {

// 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();

}

}

(8)

8

A simple client (simplified code)

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(" 130.63.122.1 ",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();

}

}

(9)

Echo Server Client..

//client.java: client interface to server import java.io.*;

import java.net.*;

public class client {

int port_id;

String server; Socket slink;

DataOutputStream os;

DataInputStream is;

DataInputStream kbd;

public client( String args[] ) {

server = args[0];

port_id = Integer.valueOf(args[1]).intValue();

try {

slink = new Socket( server, port_id );

os = new DataOutputStream( slink.getOutputStream() );

is = new DataInputStream( slink.getInputStream() );

kbd = new DataInputStream( System.in );

}

(10)

Echo Server Client..

catch( UnknownHostException e ) {

System.err.println( "Don't know about host: " );

System.exit(1);

}

catch( IOException e ) {

System.err.println( "Could not get I/O for the connection to "+server);

System.exit(1);

} }

void communicate() {

while(true) {

try {

System.out.print("Enter Input <end to stop>: ");

(11)

Echo Server Client..

if( line.equals("end") )

{ os.close(); is.close(); slink.close();

break;

}

String line2 = is.readLine();

System.out.println("Output: "+line2);

}

catch( IOException e )

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

}

public static void main( String [] args ) {

if( args.length < 2 ) {

System.out.println("Usage: java client server_name port_id" );

System.exit(1);

}

(12)

Echo Server ...

// server.java: echo server import java.io.*;

import java.net.*;

public class server {

// public final static int PORT = 4779;

public static void main( String [] args ) {

ServerSocket server = null;

DataOutputStream os = null;

DataInputStream is = null;

boolean shutdown = false;

if( args.length < 1 ) {

System.out.println( "Usage: java server port_num" );

System.exit( 1 );

}

int PORT = Integer.valueOf(args[0]).intValue();

(13)

catch( IOException e ) {

System.err.println( "Could not get I/O for the connection to: ");

}

while(!shutdown) {

if( server != null ) {

try {

Socket client = server.accept();

System.out.println("Connected");

InetAddress cip = client.getInetAddress();

System.out.println( "Client IP Addr:

"+cip.toString());

is = new DataInputStream(

client.getInputStream() );

os = new DataOutputStream(

Echo Server ...

(14)

if( line.startsWith("end" ) ) {

shutdown = true;

break;

}

os.writeBytes(line.toUpperCase());

os.writeBytes("\n");

System.out.println(line);

}

is.close(); client.close();

}

catch( UnknownHostException e ) {

System.err.println( "Server Open fails" );

}

catch( IOException e ) {

System.err.println( "Could not get I/O for the connection

Echo Server ...

(15)

System.out.println( "Server Down" );

try {

server.close();

} catch(IOException e) {}

} }

Echo Server

(16)

Server Threads

Message Passing Facility

Server Process

Client Process

Client Process

User Mode

Kernel Mode

Threads in Action...

Multithreaded Server

(17)

Client/Server Computing

Rajkumar Buyya

(18)

Client Server Definition

n “ server software accepts requests

for data from client software and

returns the results to the client”

(19)

Network

Request

Result

a client, a server, and network

Client

Server

Client machine

Server machine

Elements of C-S Computing

(20)

Where Operations are Done

In CS Relationship “most of the

application processing is done on a

computer (client side), which obtains

application services (such as

database services) from another

computer (server side) in a master

slave configuration.

(21)

CS-Focus is on

n In client-server computing

major focus is on

SOFTWARE

(22)

Application Tasks

User Interface

User Interface

Presentation Logic

Presentation Logic

Application Logic

Application Logic

Data Requests & Results

Data Requests & Results

Physical Data Management

Physical Data Management

(23)

Presentation Logic

Application Logic

DBMS

Client Server

Network

Keystroke

Displays

Client (dumb) - Server Model

(24)

Presentation Logic

Client Server

Network

Keystroke

Processed Results

Application Logic

DBMS

True Client-Server Model

(25)

Client Server

Network

Processed Queries

Processed Results

Application Logic

DBMS

Application Logic

Presentation Logic

Distributed Client-Server Model

(26)

n

Client-server computing is distributed

access, not a distributed computing.

(27)

calling

procedure

called

procedure

results=

bar(arguments)

results=

bar(arguments)

client stub

network transport

server stub

network transport

calling

procedure

(client)

called

procedure

(client)

results=

bar(arguments)

Network

Remote Procedure Call

Local Procedure Call

results

arguments resultsarguments results arguments

request message reply message reply message request message

RPC Look and Feel like Local Calls

(28)

Client Program

Client Waiting

RPC Call

with Request

return ( )

reply Request Completed

return() answer

Service Call

Invoke Service

Service Daemon Listening

Network

Client Machine Server Machine

Service Executes

May be the same machine

Flow Control in a Sychronous RPC

(29)

Server Threads

Message Passing Facility

Server Process Client Process

Client Process

User Mode

Kernel Mode

Multithreaded Server

(30)

Categories of Servers

n File Server

n Data Server

n Compute Server

n Database Server

n Communication Server

n Video Server

(31)

File Server

n

File Servers manage a work group’s application

and data files, so that they may be shared by the

group.

n

Very I/O oriented

n

Pull large amount of data off the storage

subsystem and pass the data over the network

n

Requires many slots for network connections

and a large-capacity, fast hard disk subsystem.

(32)

Compute Server

n

Performs Application logic processing

n

Compute Servers requires

c

processors with high performance capabilities

c

large amounts of memory

c

relatively low disk subsystems

n

By separating data from the computation

processing, the compute server’s processing

capabilities can be optimized

(33)

Data Server

n

Data-oriented; used only for data storage and

management

n

Since a data server can serve more than one

compute server, compute-intensive applications

can be spread among multiple severs

n

Does not prefer any application logic

processing

n

Performs processes such as data

validation, required as part of the data

management function.

n

Requires fast processor, large amount of

memory and substantial Hard disk capacity.

Data Server

Compute Server

(34)

Database Server

n

Most typical use of technology in client-server

n

Accepts requests for data, retrieves the data from

its database(or requests data from another

node)and passes the results back.

n

Compute server with data server provides the

same functionality.

n

The server requirement depends on the size of

database, speed with which the database must be

updated, number of users and type of network

used.

(35)

Communication Server

v

Provides gateway to other LANs,

networks & Computers

v

E-mail Server & internet server

v

Modest system requirements

F

multiple slots

F

fast processor to translate

networking protocols

(36)

Internet Server

Internet Server

PC client

UNIX workstations

Local Area Network

(37)

S Q L * Forms

SQL *Net TCP/IP

SQL *Net TCP/IP

ORACL E

UNIX Server

SQL *Net TCP/IP

SQL * Forms

ORACLE

Distributed processing

application connects to remote database

Distributed database application connects to local database which connects to remote database

Database Configurations

(38)

File servers

groupware

Distributed

objects

Database servers

TP monitors

1998

1990 1994

1986

1982

First Wave Second Wave Third Wave

Intergalactic era

client/server

Ethernet era

client/server

Client-Server Waves

(39)

Client Middleware Server

GUI/OOUI

Objects

Groupware

TP monitor

DBMS

DSM

Operating System

SQL/IDAPI TxRPC Mail ORB

NetBIOS TCP/IP IPX/SPX SNA

Messaging Peer-to-peer Directory Security Distributed file

SNMP CMIP DME

RPC

Service Specific

DSM

NOS

Transport Stack

Operating System

DSM

The Client/Server Infrastructure

References

Related documents

The program would also cover a useful practical case when the choice in a tree logit (or other RNEV special case) model was known only as a member of a subset... (1985)

After the analysis values of different plan and different column cross-section with and without fluid viscous dampers, the response quantities are obtained for bare frame

Are used for this definition in computer terms of a separate computer programs, a software application delivery to ask that terminal servers?. Available for database processing

Noun in a sentence. Fred likes skating. Fred goes skating every day with Raj. Fred likes skating. He goes skating every day with Raj. Raj has new skates. Raj uses his new skates

• A common effort to ensure development partner funds build and strengthen Somaliland capacity and institutions in line with Somaliland’s Public Sector Reform strategy and PFM

Select the Team Leave Bookings menu item and then select the time period for which you wish to view leave history, along with any specific Leave Code you are interested in

These social constructionist theories are used to frame understandings of gender development in the current study, but the theories are also nuanced by including perspectives

Satellite-based nighttime lights data depicted here, represent a possibility for a border-breaching, interdisciplinary approach that may hold the promise to allow

In the analysis of insurance sector development and economic growth in Nigeria by Oke (2012), using a modified model used by Curak, Loncar and Poposki (2009), the study

Of the 166 patients approached for participation at Kufstein County Hospital, 60 declined routine ePRO assessments at home; 55 chose autonomous data entry via the internet

Below are presented, the formal Creep function of Kelvin generalized; the Carson-Laplace transform process for the determination of the relaxation function;

The computer services industry provides packaged software products, professional computer services, computer processing services, database services, computer repair and

Therefore the research work was done with the things in mind and also using programming the theme to make a computer application which implements “Civil Logic”(

The two data sets have been accepted by the Danish Maritime Authority and the Danish Geodata Agency and used for giving Notice to Mariners and to update Navigational Charts for

You can also access the web application from another computer of the network using the IP address or computer's name of the host computer on which the VM is installed and

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

 Names of program and class variables may be in upper or lower case, but it is a good programming practice to use all lower case names for Java primitive data types and first

– Database server: computer on which the database software resides – Citrix or terminal server: computer that supports thin client network • Application, database, and terminal

The present study found that risk behaviors such as having more male sexual partners and paying for sex were independently associated with willingness to use PrEP, echoing findings

Tujuan yang akan dicapai dalam penelitian ini antara lain : Menganalisis data yang besar, membantu memberikan informasi dari data ekspor yang diolah untuk

Independent variables were demographics of age, gender, NHPI ethnicity, education, and marital status, and current use of cigarettes, alcohol, and marijuana entered in Step 1, and

How does a client application identify a server application on another computer on the network?. By a