145
Name : Intake : Contact Details : CN3044 Network Programming

Network programing

Embed Size (px)

DESCRIPTION

ftms

Citation preview

Page 1: Network programing

Name :

Intake :

Contact Details :

CN3044

Network Programming

Page 2: Network programing

First Edition 2011

ISBN

Publish by

FTMS Consultants (M) Sdn BhdKuala Lumpur, Malaysia

www.ftmsglobal.com

Printed in Kuala Lumpur byFTMS Consultants (M) Sdn Bhd

All our rights reserved. No part of this publication may be reproduced, stored in a retrieval system or transmitted, in any form or by any means, electronic, mechanical, photocopying, recording or otherwise, without the prior written permission of FTMS Consultants (M) Sdn Bhd.

We are grateful to the academic members and module experts for permission to produce the syllabus, teaching guide and study materials of which contribute to FTMS.

©FTMS Consultants (M) Sdn Bhd2011

Page 3: Network programing

ContentsPage

1. OVERVIEW............................................................................................................................................4

2. REVISION FOR OPERATING SYSTEM...........................................................................................5

3. REVISION FOR NETWORKING, INTERNET.................................................................................9

4. OSI LAYERS AND TCP/IP SUITE....................................................................................................17

5. NETWORK SETUP AND NETWORK COMMANDS....................................................................22

6. REVISION FOR JAVA........................................................................................................................32

7. EXERCISE FOR JAVA.......................................................................................................................40

8. PROCESS THREADING AND INTER-PROCESS..........................................................................42

9. CLIENT SERVER PROGRAMMING...............................................................................................49

10. MIDDLEWARE....................................................................................................................................54

11. TCP/IP PROGRAMMING..................................................................................................................60

12. NETWORK MODELING AND SIMULATION...............................................................................70

13. KERNEL PROGRAMMING...............................................................................................................74

14. NETWORK MANAGEMENT............................................................................................................78

15. REVISION.............................................................................................................................................81

16. Reference:................................................................................................................................................85

Page 4: Network programing

OverviewOverview

Normally UEL subject taught in FTMS KL do not have any guide books, thus the reason in 2011, Mr. Trevor wishes to have guide books for UEL students on UEL subjects.

As such this exercise will be carry out term by term and the lecturers teaching the given subjects will need to update their respective guide book for that given term.

And if all goes well by the end of the year all the books in FTMS will have been updated including UEL.

Thus I, Sola Lee was allocated this subject Network Programming as I have been teaching this subject for two (2) terms now.

CN3044 is a 3rd year subject and student have a prerequisite of SD2054 (Software Development) which in turn require SD1042 (Introduction to Software Development).

The topics will initially revise basic concept like the operating system and networking and internet and the OSI seven (7) layers.

Then the guide will briefly introduce the skills of setting up a simple network and windows network command commonly used networking. The main language used in this course will be Java as such the guide book will do a revision on Java which covers two (2) chapters even thought Java has been taught before in SD2054.

The guide book will then discuss on process threading.

Then the guide book will go into client server which will cover both web and socket programming.

Then the guide book will continue briefly on middleware, TCP/IP programming, network modeling and network simulation.

Then the guide book will end with kernel programming and network management.->

Page 5: Network programing

Overview

Page 6: Network programing

Chapter 01

Revision for Operating System

1. Introduction2. Hardware3. Software4. Process Management5. Input and Output Management6. Storage Management7. Networking8. Security

Page 7: Network programing

Chapter 1- Operating System

Introduction to Operating System (OS)

Introduction

A computer can be divided into 2 main sections; the hardware and the software.

The hardware is separated into input, process, output and storage. Each of the individual hardware has a BIOS (Basic Input Output System) used by the operating system (OS) to communicate with the devices.

The user interacts with the application software (or any other software) which in turn interacts with the operating system and using the BIOS the operating system will interact with the hardware.

Software

User

Application Software

UtilitySoftware

EntertainmentSoftware

Etc

Operating System

BIOS

Hardware Machine

An OS is set of software that runs on computers and manages all hardware and software activities in a computer.

The physical appearance of the computer can be any from a hand phone to a super computer. All computers need to have an operating system that manages its activity and resources.

Examples of OS are; Windows 7, Windows Vista, Windows XP, Macintosh, Linux Red Hat, UNIX, Solaris, etc…

7/117

Page 8: Network programing

Chapter 1- Operating System

Regardless of the OS; they all perform the same set of roles.

The following are the main role of an OS;

1. Process Management2. Input and Output Management3. Storage Management4. Networking5. Security

Process Management

There are many processing running in a computer at the same time. This is called multi processing. The OS will manage and allocate memory and CPU time to each process.

Input and Output Management

There are devices connected to the computer and signals are constantly either coming in or going out of a computer. The OS dedicated a section of the memory for each device and control the incoming or outgoing signals to and from the devices.

Storage Management

There are two main storages in the computer; primary storage and the secondary storage.

The primary storage is a short term memory a.k.a. RAM and it requires the present of electricity to keep the information intact.

The secondary storage refers to any other long term storage that need not have electricity to store the information. They are devices like the hard disk, flash drive, CD or DVD, etc…

The file system such as FAT32, NTFS and many more are created and managed by the OS system to ensure data placed in a media are productive.

The operating system also optimizes the secondary storage using technologies like virtual memory where unused space secondary storage can be converted for the use of the RAM.

Networking

Most OS now days come with network ability. Here the OS will have network features and setup such as IP address, sub-mask, gateway, etc.

8/117

Page 9: Network programing

Chapter 1- Operating System

Take note that networking can happen in the BIOS level without the presence of an OS by using physical or MAC address.

9/117

Page 10: Network programing

Chapter 1- Operating System

Security

OS will handle two (2) types of security; prevention and contingency. Prevention security such as encryption, username and password, permission setting; (Read only, Write only, Execute only) are design to prevent something bad from happening. Contingency securities such as backup, partition recovery are design to recover when such bad things happen.

->

10/117

Page 11: Network programing

Chapter 02

Revision for Networking, Internet

1. Topology2. LAN/ MAN & WAN3. Protocols4. Open and Close System5. Server Operating System6. Network Architecture7. Network devices8. Internet/ Intranet & Extranet9. Internet Application

Page 12: Network programing

Chapter 2-Networking

Introduction to Networking

Computer networking refers to the ability to join two (2) or more computers using some sort of media to enable the computers to exchange information.

The advantages of network will be; 1. To share information and resources2. Sharing resource will reduce cost3. Sharing information will speed up processing.

The disadvantages of network will be; 1. Increase the risk of data corruption and intrusion.2. Information sharing will reduces privacy.

It is important for a network person to understand how network are describe; for example the following phase:

“I have a client server LAN network running an intranet application on a Windows 2008 server. I have about 200 devices connected into a Ethernet network.”

Network computers can be describe in seven (7) ways; Topology, (Geographical factor) LAN/ MAN & WAN, Protocols, Type of System (Open or Close), Server Operating System and Network Architecture

1. Topology

There are two (2) types of topology; Physical and Logical.

Physical Topology simply refers to how computers physically connected in a network.

There is basically four (4) different type of topology; The Star, Bus, Ring and Mesh.

All other hybrid topology is a combination of the above topologies. For example a tree topology is a combination of a bus and star topology.

Each topology has its own advantages and disadvantages.

For example:

The star topology is the easier, to setup and maintain but due to the connective nature of star, if entire network will be down if the central connection is down.

12/117

Page 13: Network programing

Chapter 2-Networking

Logical Topology refers to how data are transferred from 1 computer to another without regards to the physical topology. There are two types of logical topology; shared media and token based.

In a shared media topology a.k.a. “Ethernet Network”, all devices listens to the media for traffic, when it is clear the device will drop their data into the network. The advantage is speed but it also means they will have a high collision rate.

In a token based topology all devices listens to a token that goes around to each devices. When the token arrive the device will drop their data in the token. The disadvantage is a slower network but it also means they will have zero collision rate and high bandwidth per device.

The relationship between physical and logical topology

Twisted pair Ethernet is a logical bus topology can be implemented in a physical star topology layout.

Most token base logical topology used physical ring topology but this is not always true as IBM's Token Ring is a logical ring topology can be implemented in a physically a star topology.

2. LAN/ MAN & WAN

LAN - Local Area Network

A LAN connects network devices over a relatively limited short distance. LANs are also typically owned, controlled, and managed by a single person or organization.

MAN – Metropolitan Area Network

A MAN connects network devices within the distance of a town or city. MANs are owned by the town or city and they normally form the backbone for many LAN.

WAN - Wide Area Network

A WAN connects network devices over a large physical distance. WANs are not owned by any one organization but rather exist under collective or distributed ownership and management.

3. Protocols

13/117

Page 14: Network programing

Chapter 2-Networking

There are a few primary network protocols utilized in networks these days are such as; TCP/IP, AppleTalk, ATM, DLC, IrDA, IPX/SPX and NetBEUI. We will briefly discuss only the commonly used protocols; TCP/IP, AppleTalk, ATM and IPX

Transmission Control Protocol/Internet Protocol (TCP/IP)

TCP/IP suite is a standard protocol used in inter-networking protocol commonly used to join many different types of computers. The TCP/IP suite uses only four (4) layer mode.

AppleTalk

This is a protocol suite designed for communication among Macintosh computers.

Asynchronous Transfer Mode (ATM)

ATM is a network protocol that always transmits very fast data in a fixed predictable length thus mostly used for voice, video, and data communications. The ATM protocol guarantees good service over any network regardless of the bandwidth and traffic.

Inter-network Packet Exchange/Sequenced Packet Exchange (IPX/SPX)

IPX defines addressing for the NetWare network with SPX providing security and reliability to the IPX protocol. IPX provide connectionless link using datagram. SPX provides a connection oriented link. Microsoft devices use NWLink to connect to IPX/SPX probably to access a NetWare server.

4. Open and Close System

There are two (2) type of system that normally uses a network; close system or open system.

A close system will control all access to the information usually through a single access point. Information is only made available within the organization. A close system when applying internet will use the Intranet application.

14/117

Page 15: Network programing

Chapter 2-Networking

An open system does not control access to the system thus there is a free flow of information to anyone. An open system when applying internet will use the Internet application.

A close system now a days cannot exist effectively, thus many close system will setup a semi-close system. Here only the authorized individual will have access to a restricted amount of information needed only by that individual. Such a system when applying internet will use the Extra-net application.

15/117

Page 16: Network programing

Chapter 2-Networking

5. Server Operating System

Network servers are special computer with the tasks of maintaining and monitoring a network thus they do not run many end user applications but they do have critical roles as they normally runs the database application, occasionally use as a file server or as a print server.

There are basically two (2) server operating system normally used in a network server; Linux (UNIX) and Windows. Mac OS X is actually built on a UNIX operating system.

Linux operating system is commonly used for mission critical system. As they are believe to have higher security and are more robust and they are the cheapest or free.

Windows operating system is commonly used for large network where ease of setup and maintenance are required but they are more expensive.

6. Network Architecture

Network architectures refer to the relationship between one (1) computer to the other computer connected to it, this is usually determine by the software or at some extent control by the hardware.

There are basically three (3) network architecture; peer to peer (P2P), client server and host and terminal. One computer could be running all the three different architecture simultaneously.

1. Peer to peer

In this architecture, both the computers are seen as equals and they do not need each other expect for sharing of information.

If either of the computer shut down it will not affect the other computer. Examples of a peer to peer application will be the windows explorer, bit torrent, etc.

2. Client Server

In this architecture, both the computers are seen as equals but the server has certain processing ability that they client needs. Therefore the client will request from the server and

16/117

Page 17: Network programing

Chapter 2-Networking

the server will process the required information and return the result back to the client.

If either of the computer shut down it will not affect the other computer, except that the client can no longer access the server services. Examples of a client server application will be the internet (www) application, email, most online games, etc.

17/117

Page 18: Network programing

Chapter 2-Networking

3. Host and Terminal (Dummy Terminal)

This architecture is similar to client server except that the dummy terminal (client) depends 100% on the host (server) connection. The dummy terminal cannot do any major processing except for basic input and output task, everything else comes from the server.

If the host shut down then the dummy terminal will be totally useless. Examples of a peer to peer application will be the remote connection.

18/117

Page 19: Network programing

Chapter 2-Networking

Introduction to Internet

Internet (inter-networking) refers to the ability of a network to connect to another network. Take note that internet does not equals computer networking. Computer networking connects computers together where as internet connect different network together.

Internet Application

There are five (5) internet applications that could be implemented in an organization; they are email, newsgroup (UseNet), ftp, telnet and www.

Email

Email is an application design to send message using a store and forward manner.

Email client is like Thunderbird, Outlook, etc…

The email client creates the message and sent it to the email server via SMTP protocol. The server will then either store the message in the receivers account or forward it to the relevant email server. The receiving client will then download the message from the server via a POP protocol. Newsgroup (UseNet)

Newsgroup a.k.a. UseNet is an application design to allow different client to discuss on a topic. The function is similar to an online forum.

Most email clients comes with a newsgroup component but there are some exclusive newsgroup client like Newsreader, Binreader, etc…

The email client creates the topic or the reply and sent it to the newsgroup server via NNTP protocol. The server will then store the topic or reply in the newsgroup server. The server has the ability to arrange the tread properly base on the topic title and arrange the reply just below the statement or question. Other newsgroup client will be able to view the topic or reply and follow through with another reply.

FTP

19/117

Page 20: Network programing

Chapter 2-Networking

FTP is an application design to copy resources from a client to the server. The ftp client will view the content of a server much like a window explorer.

FTP client is like Cute FTP, Core FTP, etc…

The ftp client first connects to the server with the assigned username and password. If the server is set to allow anonymous login, the client can then enter their email as a username and the word anonymous as a password.

Once login, the server will show a list of all the resources available to the client. The client can then choose to download from the server to the client or to upload resource from the client to the server via the FTP protocol.

Telnet

Telnet is an application design for the client to remotely connect to the server as if the user is physical at the server, the client will have a virtual terminal connection.

Telnet client is like PUTTY, TeraTerm, etc…

The telnet client first connects to the server with the assigned username and password.

Once login, the telnet server will return the server screen to the client. The client will then continue to send up input signals for example mouse, keyboard, or audio to the server. The server then processes the signals and return the screen or speaker audio to the client.

Telnet does not use a protocol but special software like IBM 5250 or 3270.

WWW

WWW is an application design to links resource together.

Www client is the browser like Mozilla, Chrome, Internet Explorer, etc…Www server is the webserver like Apache, IIS, Xitamin, etc…

The user will enter a URL in the browser to specify the server and the resources. The browser will then connect to the server and pass the url to the server. The server will then interpret the URL and return the resources to the client. The browser will then display the resources for the user.

20/117

Page 21: Network programing

Chapter 2-Networking

Occasionally the url may request for a file to be process, in which case the server will run the appropriate program (php, dotNet, etc) and return the result of the process to the client.

The communication between the browser and the web server is done via HTTP.

Relevant

Network programming student needs to understand the internet application because they may need to apply them to their future organization or they may be ask to create a program other software that will interact with either the client or server application.

->

21/117

Page 22: Network programing

Chapter 03OSI Layers and TCP/IP Suite

1. Switching2. OSI3. Protocol Data Units (PDU)4. Service Data Unit (SDU)5. TCP/IP

Page 23: Network programing

Chapter 3-OSI Layers

Introduction to Switching Techniques

When a computer send a message from the sender to the receivers, most probable with will have to cross via many devices and other computers we call nodes before it reaches the destination.

There is a need to control the flow (switching) of the information from the sender to the receiver thus the switching techniques. Basically there are two (2) types of switching technique; Circuit switching and Packet switching.

Circuit Switching

Imagine a telephone call. Before the sender sent information to the receiver, the sender will make a fixed connection to the receiver. Once the receiver pick up the phone the connection becomes “temporary permanent” across the many intermediate nodes, this is call the dedicated path. The information will then flow into the dedicated path and reach the destination.

The advantage of circuit switching:

1. The information is received in the same order that it was sent by the sender.

2. There is very low chance of error.3. The speed of transmission is very fast.

The disadvantage of circuit switching:

1. The dedicated path is fixed and nobody can call the sender or the receiver until the dedicated path is removed (When the receiver close the call).

2. If the dedicated path is cut during the transmission, all information is lost.

Packet Switching

Imagine a postal office service. Before the sender sent information to the receiver, the sender, the entire message is cut and divided into small packet. And each packet is place in a separate envelope with the sender and receiver address. Then the letters are all mail to the receiver.

There is no dedicated path and each packet travels independently and will travel its own way until it reaches the destination.

The advantage of packet switching:

23/117

Page 24: Network programing

Chapter 3-OSI Layers

1. The route is very robust as there is no dedicated path.2. The sender and receiver is free to talk to another device

while transmiting.

The disadvantage of circuit switching:

3. There is high chance of error because information does not arrive in the sequence it was sent and some packet may be lost.

4. The speed of transmission is very much slower.

Introduction to OSI Layers

Open System Interconnection (OSI) is created by International Organization for Standardization (ISO) where the stages of communication (communication system) between two (2) computers are divided into many different sub stages (layered architectures).

Each stage is design to be independent from any other stage and will contain a specific task that will provide service for the above stage and receive service from the lower stage. The sender and receiver must use the same protocol to ensure that they have the same layer.

The sender’s information will flow from the sender’s top layer down to the sender’s bottom layer and then it will be transmitted to the receiver’s bottom layer and make its way up to the receiver’s top layer.

At each level, the two (2) equal layers (1 at the sender and 1 at the receiver layer) interact with each other by transmitting protocol data units (PDU).

At the top layer the original data is received, process and appended with the first PDU. The combination of a PDU with the data is called the Service Data Unit (SDU).

This SDU will in turn be passed down to the next layer which will then process it and append their PDU. Then the next layer will process and append their PDU to the previous SDU. This continues until the SDU reaches the bottom layer.

The advantages of having many layers in a system are;

1. It is easy to maintain each layer instead of maintaining a huge system.

2. It is easier to debug a system with many layers.3. It is more flexible as a specific layer can be upgrade or

change without affecting the other layers.

24/117

Page 25: Network programing

Chapter 3-OSI Layers

4. Information hiding can be achieve as the above layer do not know the task of the lower layers.

The disadvantages of having many layers in a system are;

1. Each layers are independent thus the layer may repeat task already done in other layers

2. Each layer will add in extra overhead information into the data making the information size larger then it really is.

The seven layers are; Application, Presentation, Session, Transport, Network, Data-link and Physical.

The software components in the OSI layer range from the Application, Presentation, Session and halfway through the Transport. The remaining layers; the other half of the Transport, Network, Data-link and Physical are hardware.

25/117

Page 26: Network programing

Chapter 3-OSI Layers

Application

Application layer is the first layer the user will use to connect to the network; this layer will collect the required information from the user. This layer will add in the APDU. The SDU will be passed down to the Presentation Layer.

Presentation

Presentation layer will prepare the user’s information for the network, task such as encoding the information into specific network code. An example will be to convert from ASCII to UNICODE. Encryption is also done at this level. This layer will add in the PPDU. The SDU will be passed down to the Session Layer.

Session

Session layer handles end to end communication, here information about the sender and receiver are confirmed then placed into PDU. The SDU will be passed down to the Transport Layer.

Transport

Transport layer will break down the SDU into smaller even packet. Each packet will then be given a sequence number and a PDU. Each of SDU is then slowly send to the Network Layer.

Network

Data going from the sender to the receivers usually pass through a few other devices or switches we call nodes. The switching technique is determined at this stage. Network layer handles node to node communication, here information about the current node and the next node are confirmed then placed into PDU. The SDU will be passed down to the Data-Link Layer.

Data-link

Data-Link layer has two (2) tasks; synchronizes the SDU for transmission usually in the form of buffered the data and check for errors. Error checking algorithm such as even or odd parity information is place in the PDU. The SDU will be passed down to the Physical Layer.

Physical

This is the final layer that converts the SDU into binary bits suitable for the media. The converted binary will then be

26/117

Page 27: Network programing

Chapter 3-OSI Layers

transmitted down the media to the receiver; it could be just another node or the final destination for the SDU.

27/117

Page 28: Network programing

Chapter 3-OSI Layers

Introduction to TCP/IP Layers

TCP/IP model a.k.a. Internet Protocol Suite a.k.a. Internet Model a.k.a. the Department of Defense Model.

Please take note that the TCP/IP model is very different from the OSI model.

1. TCP/IP model was created before the OSI model.2. TCP/IP model is an actual real live model where as OSI is

a reference model.

Just like the OSI layer the TCP/IP model also practice layered architectures but instead of having seven (7) layers the TCP/IP has only four (4) layers.

Application Layer (process-to-process): This is the scope within which applications create user data and communicate this data to other processes or applications on another or the same host. The communications partners are often called peers. This is where the "higher level" protocols such as SMTP, FTP, SSH, HTTP, etc. operate.

Transport Layer (host-to-host): The Transport Layer constitutes the networking regime between two network hosts, either on the local network or on remote networks separated by routers. The Transport Layer provides a uniform networking interface that hides the actual topology (layout) of the underlying network connections. This is where flow-control, error-correction, and connection protocols exist, such as TCP. This layer deals with opening and maintaining connections between Internet hosts.

Internet Layer (internetworking): The Internet Layer has the task of exchanging datagram’s across network boundaries. It is therefore also referred to as the layer that establishes internetworking; indeed, it defines and establishes the Internet. This layer defines the addressing and routing structures used for the TCP/IP protocol suite. The primary protocol in this scope is the Internet Protocol, which defines IP addresses. Its function in routing is to transport datagrams to the next IP router that has the connectivity to a network closer to the final data destination. The switching technique is determined at this stage.

Link Layer: This layer defines the networking methods within the scope of the local network link on which hosts communicate without intervening routers. This layer describes the protocols used to describe the local network topology and the interfaces needed to affect transmission of Internet Layer datagrams to next-neighbor hosts. (cf. the OSI Data Link Layer).

28/117

Page 29: Network programing

Chapter 3-OSI Layers

->

29/117

Page 30: Network programing

Chapter 04Network Setup and network commands

1. Network Setup2. Design stage3. Implementation stage4. Security and Backup stage5. Network Commands

Page 31: Network programing

Chapter 4-Network Setup

Step by step guideline on how to setup a network.

There are three (3) stages; design; implement and security.

Design stage

1. Create a clear floor plan.

You can either draw a floor plan for the building or room where the network will be setup or obtain the blue print from the developer.

It will be best to include as much detail as possible especially the measurement (width, height and length) of the major component.

2. Categories the departments

Make a copy of the floor plan and indicate the department and person in charge of that department in the floor plan.

This will help identify the required software and hardware and also help you setup the security features later.

3. Identify the location of each hardware

Make a copy of the floor plan and indicate the location for every computer and other devices. Give a unique name for each computers or devices and keep a list of all the hardware specification for each computer or device.

If you are using a static IP address then start to allocate the IP address.

Furniture is not necessary but it may be helpful when you need to draw the connection later.

4. Identify the required software

For each computer or device list;

1. Identify clearly the operating system

2. Identify all other application required for that computer. It is important also to identify the license number and its expiry date (if any).

31/117

Page 32: Network programing

Chapter 4-Network Setup

3. If possible try to separate the system partition and the data in different storage device

32/117

Page 33: Network programing

Chapter 4-Network Setup

5. Connect all the network devices via the selected media.

Decide the media to connect all computers and devices. Identify all necessary network devices for the network. Make a copy of the floor plan and indicate the location of the existing network point (if any) and network devices and draw a line to join the computer to the device.

If you are using a cabled network, write the estimate length required. If you are using twisted pair cable, make sure you know if you need a “straight through” or a “cross over” cable.

If you are using a wireless network, write the furthest distance between the computers to the Access Point.

Implement stage

1. Base on the design setup the connection media (cable or wireless)

If there is an existing network point, mark each end of the network point with the unique computer name. If you are using cable connection remember to make it longer to give extra allowance for change. Mark each end of the cable with the unique computer name.

2. Setup the computer OS, Application and network

If possible have all computers in one place, insert in the network interface card (NIC) and install the operating system and application for each computer. Remember to install the anti-virus program.

If you are using a static IP address you can then setup the IP address, sub-mask, gateway and DNS address.

Once finished carry the computers physically to the respective place, connect it up to the network.

3. Setup the File Server and Print Server in the server

File server is a computer where people can store and share their files easily in a network. If use properly this will greatly reduce redundancy and increase productivity of a office system.

Print server is a computer that will handle any printing job from any computer to any printer in the organization. The

33/117

Page 34: Network programing

Chapter 4-Network Setup

print server will pool all printing task and allocate them to the respective printer. Many organizations place a printer counter in the print server base on the login to keep track of the printing cost.

34/117

Page 35: Network programing

Chapter 4-Network Setup

Security and Backup stage

1. Setup the username and password for each computer to control access

The username and password can be setup in three (3) ways;

1. BIOS username and password; set up via the BIOS before the OS is activated.

2. Operating System username and password; setup in the operating system when the user login

3. Domain Access Control; setup in the server, where the user will log into the server with a username and password, and the server will determine what the client can or cannot do once they are log in.

2. Setup the user privilege (authorize tasks) for each Computer

Once the user has login either as administrator or other user there will be a big difference between what the administrator and other user can do. For example the administrator will be able to change the network setup whereas the other users will not.

To do this effectively, go back to the department floor map, then draw a organization chart (if one does not exist), then sit down with the users and decide what are the authority of each person or department: What they can and cannot view and what they can and cannot do

Most operating system comes with three (3) privileges; Read, Write and Execute privileges. From these privileges you can derive basically eight (8) set of privileges:

1. No privileges2. Read Only3. Write Only4. Execute Only5. Read and Write Only6. Read and Execute Only7. Write and Execute Only8. Read and Write and Execute

3. Backup each computer’s System and Data

35/117

Page 36: Network programing

Chapter 4-Network Setup

If possible the system partition should be separated from the data partition. This is because the system partition can always be copied using partition software such as Norton Ghost or My-Backup and store in a DVD. Major changes to the system partition are rare.

36/117

Page 37: Network programing

Chapter 4-Network Setup

User data however cannot be back-up so easily because of its dynamic change. The are two way to handle this;

1. To have a separate hard disk for each computer.

2. To have a file server and a folder for each user. Then have the user backup their work to the file server daily. Then have a periodic (weekly) backup of all folders in the file server to a DVD.

4. Implement Backup Policy

Once everything is in place and the network is running smoothly it is time to finish up the last part of work; to make a good backup policy.

Each user at every department must be train to understand how the network works and how they can take advantage of the network.

Then they need to be informed of the possible danger; virus and hardware malfunction. Then they need to be made aware of how these can cost them their time and effort.

Then introduce to them the backup policy and how the backup policy can prevent or reduce the damage that the above danger could bring. Then explain to the user’s their role in the backup policy.

5. Monitor the network

Every network in the world will change both internally and externally. Internally the changes may come in the form of growth in size and services. Externally change may come in the form of external government policy, new treats such as new virus or hardware dugs.

Every change bring new risk or new opportunity that can be considered, a simple SWOT can help with the risk and change management.

37/117

Page 38: Network programing

Chapter 4-Network Setup

Network Commands (Windows XP)

Setup a network is usually in theory very easy but occasionally there are times when there is a bug and having knowledge of network commands used normally in the command prompt (command interface) can be very helpful.

The following are dos command commonly used in network environment:

ArpFingerHostnameIpconfigPathpingPingNbtstat

NetNetstatNslookupRouteTracert / Traceroute

1. ARP: (Address Resolution Protocol) Use to show the IP address and the physical address (MAC Address) of that IP address.

C:\ >arp -a

Interface: 192.168.11.222 --- 0x40002

Internet Address Physical Address Type 192.168.11.1 00-e0-16-87-21-83 dynamic 192.168.11.201 00-50-da-bb-1c-5b dynamic

An example of how to change the 220.0.0.160 IP address to 220.0.0.161

C:\ >arp -s 220.0.0.161 00-50-da-bb-1c-5b

2. Finger: (Finger Information Protocol) using the email address allows you to find sometimes personal information about a user. Most server will disable this feature thus you will need to be in administrator mode to test this feature out.

C:\ >finger [email protected]

[[email protected]]

Name : Sola LeePhone : 111-222-3333Affiliation : Senior, Computer Sciencelogin name : hantuaccount used : Mon Apr 30 22:36 (7 days 13 hours ago)e-mail : [email protected] : Graduating in Curtin University of Technology

38/117

Page 39: Network programing

Chapter 4-Network Setup

3. Hostname: Return to you the name of the pc you are running on.

C:\ >hostnamesolaleePC

4. Ipconfig: Ipconfig is a MS-DOS utility that can be used from MS-DOS and a MS-DOS shell to display the network settings currently assigned and given by a network. This command can be utilized to verify a network connection as well as to verify your network settings.

C:> ipconfig

Windows IP Configuration

Ethernet adapter FTMS:

Connection-specific DNS Suffix . :IP Address. . . . . . . . . . . . : 92.168.11.222Subnet Mask . . . . . . . . . . . : 255.255.255.0Default Gateway . . . . . . . . . : 192.168.11.1

5. Pathping: Pathping is a DOS utility enables a user to find network latency and network loss.

C:\>pathping localhost

Tracing route to leeujan [127.0.0.1]over a maximum of 30 hops: 0 localhost [127.0.0.1] 1 localhost [127.0.0.1]

Computing statistics for 25 seconds... Source to Here This Node/LinkHop RTT Lost/Sent = Pct Lost/Sent = Pct Address 0 localhost [127.0.0.1] 0/ 100 = 0% | 1 0ms 0/ 100 = 0% 0/ 100 = 0% localhost [127.0.0.1]

Trace complete.

6. Ping: Ping allows a user to ping another network IP address. This can help determine if the network is able to communicate with the network.

C:\>ping localhost

Pinging leeujan [127.0.0.1] with 32 bytes of data:

Reply from 127.0.0.1: bytes=32 time<1ms TTL=128Reply from 127.0.0.1: bytes=32 time<1ms TTL=128Reply from 127.0.0.1: bytes=32 time<1ms TTL=128Reply from 127.0.0.1: bytes=32 time<1ms TTL=128

39/117

Page 40: Network programing

Chapter 4-Network Setup

Ping statistics for 127.0.0.1: Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),

Approximate round trip times in milli-seconds: Minimum = 0ms, Maximum = 0ms, Average = 0ms

7. NBStat: This command displays protocol statistics and current TCP/IP connections using NBT (NetBIOS over TCP/IP).

NetBIOS created in 1980s for only small networks (12 computers). Some old applications still use NetBIOS but this work well in today's networks (1000s of computers). When properly configured, NBT allows those old applications to be run on large TCP/IP networks (Internet) without having to change.

C:\>nbtstat -a 192.168.11.222

FTMS:Node IpAddress: [192.168.11.222] Scope Id: []

NetBIOS Remote Machine Name Table

Name Type Status --------------------------------------------- LEEUJAN <00> UNIQUE Registered LEEUJAN <20> UNIQUE Registered WORKGROUP <00> GROUP Registered WORKGROUP <1E> GROUP Registered

MAC Address = 70-5A-B6-17-71-B4

8. Net: It is used to set, view and determine network settings. You can even send message over a network to another pc. You need to know the switches to use this command effectively:

C:\>net send * "Testing"The message was successfully sent to domain WORKGROUP.

C:\>net configThe following running services can be controlled:

Server Workstation

The command completed successfully.

9. NetStat: s used to display the TCP/IP network protocol statistics and information on the current machine.

C:\>Netstat

40/117

Page 41: Network programing

Chapter 4-Network Setup

Active Connections

Proto Local Address Foreign Address State TCP leeujan:3034 computerhope.com:http ESTABLISHED TCP leeujan:3035 ni-in-f157.1e100.net:http ESTABLISHED TCP leeujan:3036 ni-in-f157.1e100.net:http ESTABLISHED TCP leeujan:3037 ty-in-f118.1e100.net:http ESTABLISHED TCP leeujan:3038 ni-in-f164.1e100.net:http ESTABLISHED TCP leeujan:3039 ty-in-f101.1e100.net:http ESTABLISHED

10. NsLookUp: enables a user to do a reverse lookup on an IP address of a domain or host on a network. Running nslookup without specifying an IP address or domain name will display your routers server and address. To get out of the > prompt type exit and press enter.

C:\> NsLookUp

Server: nsp.mykris.netAddress: 202.133.99.11

Non-authoritative answer:Name: localhostAddress: 127.0.0.1

> exit

11. Route: The route MS-DOS utility enables computers to view and modify the computer's route table.

C:\> route

===========================================================================Interface List0x1 ........................... MS TCP Loopback interface0x40002 ...70 5a b6 17 71 b4 ...... Atheros AR8131 PCI-E Gigabit Ethernet Controller - Packet Scheduler Miniport====================================================================================================================================================Active Routes:Network Destination Netmask Gateway Interface Metric 0.0.0.0 0.0.0.0 192.168.11.1 192.168.11.222 30 127.0.0.0 255.0.0.0 127.0.0.1 127.0.0.1 1 192.168.11.0 255.255.255.0 192.168.11.222 192.168.11.222 30

41/117

Page 42: Network programing

Chapter 4-Network Setup

192.168.11.222 255.255.255.255 127.0.0.1 127.0.0.1 30 192.168.11.255 255.255.255.255 192.168.11.222 192.168.11.222 30 224.0.0.0 240.0.0.0 192.168.11.222 192.168.11.222 30 255.255.255.255 255.255.255.255 192.168.11.222 192.168.11.222 1Default Gateway: 192.168.11.1==========================================================================Persistent Routes: None

42/117

Page 43: Network programing

Chapter 4-Network Setup

12. Tracert (Windows)/ Traceroute (Unix):

The tracert command is a network command to help determine network related issues or slowdowns. Using this command you can view a listing of how a network packet travels through the network and where it may fail or slow down. Using this information you can determine the computer, router, switch or other network device possibly causing your network issue

C:\> tracert www.google.com

Tracing route to www.l.google.com [64.233.181.99]over a maximum of 30 hops:

1 1 ms 1 ms 1 ms 192.168.11.1 2 <1 ms <1 ms <1 ms 192.168.200.2 3 1 ms 1 ms * static-202-133-104-78.mykris.net [202.133.104.78] 4 * 3 ms 4 ms static-122-0-16-73.mykris.net [122.0.16.73] 5 5 ms 4 ms * static-122-0-18-41.mykris.net [122.0.18.41] 6 8 ms * * static-122-0-16-201.mykris.net [122.0.16.201] 7 7 ms 4 ms 7 ms global.hgc.com.hk [218.189.12.237] 8 41 ms 41 ms 85 ms global.hgc.com.hk [218.189.8.101] 9 42 ms 41 ms * 218.189.5.21 10 44 ms 42 ms 45 ms 218.188.104.202 11 45 ms 44 ms 148 ms 209.85.241.58 12 * * * Request timed out. 13 47 ms * * 209.85.250.237 14 56 ms * 65 ms 209.85.243.142 15 * * * Request timed out. 16 * 48 ms 49 ms ni-in-f99.1e100.net [64.233.181.99]

Trace complete.

->

43/117

Page 44: Network programing

Chapter 05Revision for Java

1. Installation2. Compile3. SET path4. run java file5. Object Oriented concept6. UML Class Diagram7. Class and Object

Page 45: Network programing

Chapter 5-Java

Introduction

In this subject (Network Programming), knowing Java programming language is crucial as most of the coding will be done in Java.

This guide-book assumes that the student has taken the required pre-requisite as such these two (2) chapters sole purpose is to briefly revise Object Oriented Concept and java programming language.

Introduction to install Java Assuming OS is: Windows XP ProfessionalJDK version is: jdk1.6.0_01

1. Download the latest version of the Java Development Toolkit (JDK) from the Java website. At the time this guidebook was written the latest JDK file was call jre-6u7-windows-i586-p-s.exe

2 Double click and run the file icon or the executable file.

Then click on Run when you see the following screen.

3 The installer will start up the installation wizard and you will see the following screen.

Click on Accept.

45/117

Page 46: Network programing

Chapter 5-Java

4 The wait for the installation to finish.

5 Click on finish.

6 Click on start, choose Run and type “cmd” in the command box

In the command prompt type “javac. exe”

Microsoft Windows XP [Version 5.1.2600](C) Copyright 1985-2001 Microsoft Corp.

C:\>javac

'javac' is not recognized as an internal or external command, operable program or batch file.

Find the java folder that contains the javac.exe file.7 Open up “My Computer” or

“Windows Explorer” and go to

C:\Program Files\Java\jdk1.6.0_01\bin

Copy and Paste the file path C:\Program Files\Java\jdk1.6.0_01\bin

46/117

Page 47: Network programing

Chapter 5-Java

The next thing to do will be to set the window system path to the JDK folder so that Windows OS will know where to find for the file when it is needed.

8 If you have administrator authority then do the following:

Right click on My Computer, select Properties and Advance Tab.

Then click on Environment Variables

If you do not have the administrator authority then go to 11

9 Inside the System variable field select PATH

Then click on Edit.

Place your cursor on the last position (Press End)

Then append the java full path“C:\Program Files\Java\jdk1.6.0_01\bin”to the end of the current path

Click on OK10

Try 6 again You should see a long list of error. This shows that the compiler works

11 If you do not have administrator authority then do the following:

Click on start, choose Run and type “cmd” in the command box

In the command prompt typeC:\> path=%path%; C:\Program Files\Java\jdk1.6.0_01\bin;

Then type:C:\> javac

You should see a long list of error. This shows that the compiler works

47/117

Page 48: Network programing

Chapter 5-Java

Code and run a java program.

1. Open up a note pad and save it as Test.java

2. Type the following code

public Test{ public static void main(String args[]){ System.out.println(“Hello Java World”); }}

3. Save the Test.java file to any location where you can later access it. Preferable at any root drive C or D or E.

4. Click on start, choose Run and type “cmd” in the command box

5. Go to the root drive

6. Type a dir and press EnterYou should be able to see the Test.java file

7. Type at the command prompt javac Test.javaC:\> javac Test.java

8. If there is no error then you should have successfully compiled the java file

9. Type a dir and press EnterYou should be able to see two (2) files; Test.java file and

Test.class

10.Type java Test.javaYou should see the result “Hello Java World”.

Introduction to Object Oriented (OO) Programming Concept

Object Orientation is where the real world can be seen and modeled as a system of interacting objects. Objects are like a car, a mother, a driver, a lorry, etc…

All objects must be built from a class. A class is a group of objects that shares a common state, behavior and semantics. For example a car and lorry can be built from a class call vehicle. A mother and driver can be built from a class call Person.

48/117

Page 49: Network programing

Chapter 5-Java

A class is therefore an abstraction of a real world objects created exist in the coding and an object is an instance of a class existed during runtime.

Class is divided into two (2) sections; the properties and methods. The ability to combine the properties and methods in a class is call encapsulation.

1. The properties or attributes or member variables. The properties define the state of a given object. There are different types of properties; class attribute and instance attribute.

2. The methods or behavior or operation or member function. The methods are action that the object can perform on itself. There are different types of methods; class operation, instance operation, constructor, destructor, modifiers (setters) and selectors (getters).

In OO approach, objects are said to message one another, asking the receiving objects to perform a method within itself on itself. For example the driver can sent a message to the car object to start its engine. The mother can ask the driver to jump around. Thus the ability for an object to message another object is call messaging.

In OO there is the ability for a new class (usually call the sub class or the child class) to have almost all the properties and methods of another class (usually call the base class or super class or the parent class). This ability is call inheritance. For example an Animal class is created to hold the general characteristic for Mammal class, Reptile class, Bird class, etc…

There are different types of base class; normal class and an abstract class. Java only allows single inheritance but one can implement many interfaces.

Generalization is the ability to create a base class that contains all the general characteristic of a set of classes using inheritance. The child class is seen to have a “is a” relationship with a parent child. For example a mammal is an animal.

When there is a lot of classes arrange with multiple level of inheritance, the terms ancestor or descendent are used to describe their relationship. All descendent child will have the “is a” relationship with the parent class.

Specialization is the ability to inherit from a general class and create something different in the sub class.

49/117

Page 50: Network programing

Class Name

Chapter 5-Java

Composition is the ability of a class to contain one (1) or more different class. The outer class is seen to have a “has a” relationship with an inner child or the inner class is seen to have a “is a part of” relationship with a outer child. For example an engine has many pistons or pistons are a part of an engine.

Polymorphism is the ability for one (1) or many class to have same characteristic “on the outside” but each will produce a different outcome because they are actually different “inside”. This ability is implemented in Java using overloading, overriding, heterogeneous classes.

Overloading is the ability for one (1) class to have many methods with exactly the same name with different signatures that will give a different result.

Overriding is the ability for one (1) child class (that inherits from a parent class) to have many methods with exactly the same name and signature as the parent class that will give a different result.

UML Class Diagram and it’s representations

The following is simple scenario translate into a class diagram.

Scenario: A Person have properties call name, age.

UML Class Diagram

50/117

Person- name : String- age : Integer+ Person ()+ setName(String):void+ getName(void):String+ setAge(Integer):void+ getAge(void):Integer

Access Method

Property NameProperty Data Type

Method Name

Input Parameter Data type

Return Type

Property

Method

Page 51: Network programing

Chapter 5-Java

For the class name the standard is to use Capital Letter for the first (1st) letter and small for the subsequent letters (sentence casing). If the class name consists of two (2) words or more then the words are jointed together with the subsequent words first letter in capital. For example; for a class call Big Boy, the class name will be BigBoy.

For the property name the standard is to use small casing. Again if the property name consists of two (2) words or more then the words are jointed together with the subsequent words first letter in capital.

For the method name the standard is to use small casing except for the constructor’s and destructor’s name. Again if the method name consists of two (2) words or more then the words are jointed together with the subsequent words first letter in capital.

As class diagram are language independent, programming language keyword avoided.

51/117

Page 52: Network programing

Chapter 5-Java

Class and Object with Java

Taking from the previous class diagram and adding the following requirement; a teacher and a student are instants of Person. The teacher’s name is call Trevor aged 30 years old and the student’s name is Eric aged 20 years old.

This is the Person classes code in a file call “Person.java”

public class Person{ private String name; private int age;//================================== public Person(){name=“”;age=0;} public void setName(String x){name = x} public String getName(){return name;} public void setAge (int x){age = x;} public int getAge (){return age;}};

This is the main function that will run the classes.

public static void main(String args[]){ Person teacher; teacher.setName(“Trevor”); teacher.setAge(30); System.out.println(teacher.getName() + teacher.getAge()); Person student; student.setName("Eric"); student.setAge(20); System.out.println(student.getName() + student.getAge());}

The following will be the output for either of the above codes:

Trevor 30Eric 20

Go to http://download.oracle.com/javase/1.5.0/docs/api/ to view all the pre-define classes available in Java.

->

52/117

Page 53: Network programing

Chapter 06Exercise for Java

Page 54: Network programing

Chapter 6-Java Exercise

Study the scenario. After you understood the UML then create all the necessary class.

Scenario

A Student is a person with a name, age, gender. A student can take many subjects. A Teacher is also a person with a name, age and gender and a teacher can teach many subjects. Each subject has a name and duration. A room can accommodate 1 teacher for 1 subject and 5 students.

Create a class program call School that will accommodate 5 rooms. Give the user the ability to add in subject, a teacher and students to each room. Then list out the name of the subject, teacher and all students for each room.

Person

- name: String- age: Integer

- gender: Character

+ Person()+ Person(String, Integer, Character)+ setName(String):void+ getName(void): String+ setAge(String):Integer+ getAge(void): Integer+ setGender(Character):void+ getGender(void): Character+ show(void):void

Subject

- name: String- duration: Integer

+ Subject()+ Subject(String,Integer)+ setName(String):void+ getName(void): String+ setDuration(Integer):void+ getDuration(void): Integer+ show(void):void

Room

- teacher: Person- theSubject: Subject- students: Person [5]

+ Kelas1()+ Kelas1(Person,Subject)+ setTeacher(Person):void+ getTeacher(void):Person+ setSubject(Subject):void+ getSubject(void): Subject+ setStudent(Person, Integer):void+ getStudent(Integer) :Person+ show(void):void

School

- rooms: Room [5]

+ School()+ setRoom (Room,Integer):void+ getRoom (Integer): Room+ show(void):void+ mainMenu(void):void

->

54/117

Page 55: Network programing

Chapter 07Process Threading and Inter-process

1. Multiprocessing2. Multitasking3. Multithreading4. Concurrency Problem5. Concurrency Control6. Deadlock7. Java Thread8. Java synchronized

Page 56: Network programing

Chapter 8-Client Server

Serial (Sequential) processing

In the early days of the computer with only one (1) CPU, when there are many processes, each process can only be given to the CPU one at a time. Meaning all the other processes are queued up until the CPU is free to process it.

This is very ineffective and inefficient, thus the having more CPU will make processing faster but because CPU are expensive this was not an option until multiprocessing, multitasking and multithreading was realized.

Multiprocessing

Multiprocessing is a concept for the hardware level, if there are two (2) or more devices that require processing in one (1) computer. If the computer has only one (1) CPU then first process has to be run first and once it is completed then the second process can be run. If the computer has two (2) or more CPU then both process can be run simultaneously on two processors.

Multitasking

Multitasking is a concept for the software level where the operating system has the ability to share one CPU with many different tasks. Each task is allocated an equal time to process their work before it is “paused” and the control is passed on to the next task. Thus goes around until all tasks is done. The ability of the operating system to quickly switch between tasks gives the appearance of simultaneous execution of those tasks, even thought it is actually processing portion of each task one at a time.

Multithreading

Multithreading is similar to multitasking except that it in done inside an applications. One application can have many operations waiting for processing.

Here each operation within a single application will be divided into individual threads, and each thread theoretically has the ability to run parallel. The operating system will then divide processing time among the different thread inside each applications and also the different application.

For example, a game program may use many applications and each application might have three (3) threads (a user interface thread, a data acquisition thread, and backend engine thread). Each thread will be assigned a priority and all of the thread will be run independently from other thread.

56/117

Page 57: Network programing

Chapter 8-Client Server

Thus, multithreaded applications can have multiple tasks progressing in parallel along with other applications.

57/117

Page 58: Network programing

Chapter 8-Client Server

This is an example of a normal class (no Thread)

The source code The screen output

public class MyThread{ public String msg; public MyThread(String x){msg=x;} public void show(){ int i=0; for (i=0;i<100;i++){ System.out.println(msg); } } public static void main (String args[]){ MyThread t1 = new MyThread("Hello"); t1.show(); MyThread t2 = new MyThread("Bye"); t2.show(); }}

HelloHelloHello...HelloHelloByeBye...ByeByeBye

There are two ways to create thread in java;1. Implement the Runnable interface (java.lang.Runnable)2. By Extending the Thread class (java.lang.Thread)

Implement java.lang.Runnable

Take note that the start method is inherited from the Thread class that controls the threading sequence. Run this a few times to see the different result.

The source code The screen outputimport java.io.*;public class MyThread extends Thread{ public String msg; public MyThread(String x){msg=x;} public void show(){ int i=0; for (i=0;i<100;i++){ System.out.println(msg); } } public void run (){show();} public static void main (String args[]){ MyThread t1 = new MyThread("Hello"); MyThread t2 = new MyThread("Bye"); t1.start(); t2.start(); }}

HelloHelloHello.ByeBye.HelloHelloByeBye.HelloHello.ByeByeBye

58/117

Page 59: Network programing

Chapter 8-Client Server

Extending java.lang.Thread

Take note that the start method is inherited from the Runnable interface that controls the threading sequence. Run this a few times to see the different result.

The source code The screen outputimport java.io.*;public class MyThread implements Runnable{ public String msg; public MyThread(String x){msg=x;} public void show(){ int i=0; for (i=0;i<100;i++){ System.out.println(msg); } } public void run (){show();} public static void main (String args[]){ MyThread t1 = new MyThread("Hello"); Thread tobj1 = new Thread(t1,"Hello Thread"); MyThread t2 = new MyThread("Bye"); Thread tobj2= new Thread(t2,"Bye Thread"); tobj1.start(); tobj2.start(); }}

HelloHelloHello.ByeBye.HelloHelloByeBye.HelloHello.ByeByeBye

There are four (4) possible states of a Thread:

New (Born) - After the Thread object is created just before the start() method. The thread is considered not alive.

Runnable (Ready-to-run) - A thread start its life after the start()

method is call or after the thread returns from a another state. Here the thread is waiting for a turn on the processor. There are many ways to place a thread at this state (Sleep, Wait, etc…)

Running (Executing) - A thread is in a running means the thread

is currently executing. There is only one way to enter in Running state, the scheduler select a thread from runnable pool.

Blocked (Waiting) - A thread can enter in this state while waiting for resources that are hold by another thread.

59/117

Page 60: Network programing

Chapter 8-Client Server

Dead (Finished or Killed) - A thread is dead when it completes the method. Thread in this state cannot run again.

60/117

Page 61: Network programing

Chapter 8-Client Server

Distributed Computing

Distributed computing, happens when more then one computer (thus obviously used different storage) is used to process one (1) or many processes to achieve a common goal.

Concurrent Computing

Concurrent computing or Parallel Computing, happens when more then one processes in one (1) computer sharing the same memory yet the process are running simultaneously. This is applied through multi-programming or multi-processing; in Java this will be achieved via the use of Threads.

Concurrent computing is becoming popular due to the increases in productivity, but if badly design concurrent computing come with a price.

Concurrency problem

Serially processing will never overlap in time therefore there is not need to worry about concurrency problem. In a concurrent transaction, process overlaps each other in an uncontrolled manner can cause something bad can happen.

If all the process run in parallel and each of them are using an independent resources then concurrency problem will not occur. Concurrency problem happen when any two or more process shares a same resources.

1. The lost update problem:

If process 1, 2 and 3 reads from the same file (File A) with the value 123, then process 1 update the File X to 456. Later Process 3 also updates the value to 999.

What will happen to the update of Process 1 with the value of 456? It will be overwrite by Process 3 value of 999.

2. Non-repeatable read:

61/117

Process 1 Process 2 Process 3

File X123

Page 62: Network programing

Chapter 8-Client Server

Process 1 reads File X value of 123. Process 2 deletes File X. Process 1 now has a copy that does not officially exist.

3. The dirty read problem:

If process 1 reads the value 123 in File X and try to update it to 456, then process 2 read File X the value of 456. But something happen to process 1 and the File X value is revoke back to 123.

What will happen to the value of 456 in File X? Process 2 did not know that the actual value in File X should have been 123 and not 456.

4. Phantom read:

If process 1 needs to create a report and reads the value 123 in File X. Then process 2 updates the File X value to 456. The report of process 1 will be wrong because value if no longer 123. If process 1 is run again it will show a different result.

Concurrency control

Generally concurrency control mechanisms can be divided into three (3) ways:

1. Optimistic

This is the best method to ensure good performance. It assumes that conflicts of resources are very rare, Process 1, 2 and 3 will never read and update to File X at the same time.

When Process 1 reads File X, the file is still left open for any other process to use. Only at the last minute when Process 1 wants to update will a checking be done. If the checking proofs that a conflict will happen then it will Process 1 stop and retry again. If not too many transactions are aborted, then being optimistic is usually a good strategy.

There is basically two ways to do the checking and recovery:

Create a audit file and mark all the change with a unique number or time-stamp or id. When there is a conflict then undo the latest change from the audit file back to File X.

To make a copy of the entire File X.

62/117

Page 63: Network programing

Chapter 8-Client Server

2. Pessimistic

This is the best method but it slows down performance. Once Process 1 reads File X, the file will be block and any other process cannot touch File X until Process 1 is done.

63/117

Page 64: Network programing

Chapter 8-Client Server

3. Semi-optimistic

This is an interesting method and with good performance. Once Process 1 reads File X, the file will be block for writing. Other process can read but they cannot write to File X until Process 1 is done.

Java handles concurrency with synchronized keyword.

Synchronized uses an “ownership token” method. Every thread must have the token to process otherwise the thread will wait. If the token is free, the thread will lock the token and run his process until it finish then release again.

The source code The screen outputimport java.io.*;public class MyThread implements Runnable{ public String msg; public MyThread(String x){msg=x;} public void show(){ synchronized (this) { //lock statement int i=0; for (i=0;i<100;i++){ System.out.println(msg); } } } //lock method public synchronized void run (){show();} public static void main (String args[]){ MyThread t1 = new MyThread("Hello"); Thread tobj1 = new Thread(t1,"Hello Thread"); tobj1.start(); MyThread t2 = new MyThread("Bye"); Thread tobj2 = new Thread(t2,"Bye Thread"); tobj2.start(); }}

HelloHelloHello.ByeBye.HelloHelloByeBye.HelloHello.ByeByeBye

Deadlock

Having concurrency control also pose another problem call Deadlock. Deadlock happens when there are two (2) or processes waiting for each other to finish completing their task before they can proceed. But the problem here is because each process are waiting for each other, none will ever complete their task.

The operating system must be configured to solve a deadlock. There are two ways this can be done:

1. Design to operating system to prevent any deadlock.

64/117

Page 65: Network programing

Chapter 8-Client Server

2. Design the operating system to detect a deadlock and take an action to stop all process, release the deadlock and try again.

->

65/117

Page 66: Network programing

Chapter 8-Client Server

Chapter 08Client Server Programming

1. Advantages2. Disadvantages3. Socket Client Server4. Web Client Server

66/117

Page 67: Network programing

Chapter 8-Client Server

Client Server

As previously mentioned, Client server is one of the network architecture other then peer to peer and Host Terminal.

In a client and server architecture, there are at least two (2) separate processes; a client and a server. They may be in one or more computers.

The client will always request from a server and the server response back to the client. Normally there will be one or more client connecting to one particular server, but in some instance there is a client and server in every computer and each connecting to each other using client and server relationship.

All internet applications use client server architecture such as email, www, ftp, etc.

Advantages

1. Client server architecture distributed the processing and responsibility of a program to different computers over a network. Imagine the traditional fat server against the latest thin client. The thin server’s resources are slim and it depends entirely on different servers to handle its need.

2. Client server architecture is easier to maintain. The server can be upgraded or relocated without the need to inform the clients.

3. Data is stored on the servers is more secure and controlled. Servers can also control access and resources using username and password.

4. Centralizing data storage will make administration to the data a lot easier and reduces redundancies.

Disadvantages

1. When there are many simultaneous clients requesting from a given server, the server becomes overloaded. This will slow down the server performance at times.

2. Should an important server, the clients’ requests cannot be fulfilled thus the dependents to a server does not guarantee security.

Almost all programming languages uses Socket to code in a client server environment. A socket is a data structure that establishes

67/117

Page 68: Network programing

Chapter 8-Client Server

bidirectional communication between a server program and one or more client.

The client and server have an IP address to represent that device. The client and server will also have ports allocated by the operating system.

There will be a set of codes on the server that will be run by the server call a server codes. There will be a set of codes on the client that will be run by the client call a client codes. Both client and server will need to use socket.

68/117

Page 69: Network programing

Chapter 8-Client Server

The server main role is to create special Socket (normally call the server socket) that listens to any incoming signal from a client via a specific port number.

When a client wishes to communicate with the server, it needs to know the server IP address and the port number from which the server is listening. The client will then create a socket and link that socket to the memory out section. It will then use that socket to connect to the server.

Once the server receives a signal from the client it will then create a socket to connect to the client.

Example of Client Server using Java

Client Coding

import java.io.*;import java.net.*;public class Client{ public Client(){

Socket s = null;ObjectOutputStream out = null;try{

s = new Socket("localhost",2004);out = new

ObjectOutputStream(s.getOutputStream());out.flush();out.writeObject("Hello there");out.flush();

}catch(Exception ex){} finally{

try{ if (out != null) out.close(); if (s != null) s.close();}catch(Exception ex){}

} } public static void main(String args[]){ Client c = new Client(); } }

69/117

Page 70: Network programing

Chapter 8-Client Server

Server Coding

import java.io.*;import java.net.*;public class Server{ ServerSocket ss= null; Socket conn = null; ObjectInputStream in= null; public Server(){

try{ss = new ServerSocket(2004, 10);System.out.println("Waiting for

conn");conn = ss.accept();String hn =

conn.getInetAddress().getHostName();System.out.println("conn received from

" + hn);in = new

ObjectInputStream(conn.getInputStream());try{

String message = (String)in.readObject();

System.out.println(message);}catch(Exception ex){}

}catch(Exception ex){}finally{

try{in.close();ss.close();

}catch(Exception ex){}

} }}

Example of Web Application Client Server using PHP

Web application client server runs at a higher level, it uses HTTP to communicate between the client and the server. Even then the client and server still use Socket to communicate with each other. The default port number on the server is port 80.

The client software here will be the browser for example Internet Explorer, Mozilla, Chrome,etc. The server software will be a web server for example IIS, Apache, Xitami, etc.

The browser basically can only interpret a very few script; HTML, JavaScript and CSS.

70/117

Page 71: Network programing

Chapter 8-Client Server

To enable the browser to do more, browser plugin need to be install to enhance the ability and feature of the browser. You can also install standalone program call helper that will be able to associate it self with the browser through the MIME.

The web server must be install with the necessary programs to compile, run or interpret the server script such as PHP, dot NET framework, ASP, etc. For this study guide must have PHP interpreter install to enable the web server to run and interpret PHP scripts.

HTML Client Script (client.html)

<html><head>Web Client Test</head><body> This is a test for HTML Client. <form method="GET" action="server.php"> <br/>Usename <input type="input" type="text" />

<br/>Password <input type="input" type="password" />

<br/><input type="submit" type="Go" />&nbsp;&nbsp;&nbsp;&nbsp; <input

type="reset" type="Clear" /> </form></body></html>

Screen Output in the browser. (http://localhost/client.html)

PHP Server Script (server.php)

71/117

Page 72: Network programing

Chapter 8-Client Server

<?php echo "<br>Running on PHP Version: " . phpversion(); if (isset($_GET['username'])){$username=$_GET['username'];} if (isset($_GET['password'])){$password=$_GET['password'];} echo "<br/>Username : {$username} Password : {$password}";?>

Screen Output in the browser.

(http://localhost/server.php?username=MyName&password&=noIdea)Running on PHP Version: PHP 5.1Username: MyName Password: noIdea

Browser (Client) Source:

<br/>Running on PHP Version: PHP 5.1<br/>Username: MyName Password: noIdea

->

72/117

Page 73: Network programing

Chapter 09Middleware

1. Portability 2. Interoperability 3. Ensure Compatibility 4. Shared Common Functionality 5. Scalability6. Transactional 7. Message-oriented 8. Procedural9. CORBA using Java

Page 74: Network programing

Chapter 9-Middleware

Middleware

Many software or architecture today practices middleware. Middleware are small software normally known as layers that is combine with other middleware to form larger software.

Each middleware is created to be independent and portable. This will ensure the primary purpose of middle ware which is; Hide in-compatibility, Location independence, Usable Common functionality, portability, integrate legacy facilities, interoperability and scalability.

1. Portability - The middleware must be able to run in many different operating systems on many physical different machines anyway in the network.

2. Interoperability - The middleware must be able to run with other middleware or software to achieve a specific purpose without the compatibility issue.

The above two main objective can be further broken down into the following:

Ensure Compatibility – Middle ware must be able to cross over different version or type of software and be able to ensure compatibility. Middleware ensures seamless and easy crossover from old version or software and to the new one.

Shared Common Functionality – Most middleware are created to have a highly in demand features. If you analyze or predict that a feature is highly is demand by other application (usually a very new innovative idea) then normally a middleware is created so enable different software from different operating system to share that new feature.

Scalability– Middleware must be design so that it can handle small to large amount of simultaneous usage.

Some of the example of protocols or software built using middleware:

1. OSI 7 Layers – the OSI layer uses 7 layers to sent data from the sender to the receiver over a computer network.

2. TCP/IP Suite– the TCP/IP layer uses 4 layers to sent data from the sender to the receiver over a computer network over any network.

3. DOM (Distributed object management) – the DOM is a library of tools that can be use by any programming

74/117

Page 75: Network programing

Chapter 9-Middleware

language to access the internal components of the Windows Operating System.

4. Most Database Connectors software like Java ODBC, MySql Php ini files, etc.

5. Software used to handle remote connection like Java CORBA (Common Object Request Broker Architecture), Distributed Component Object Model (DCOM), etc

The types of middle ware are every growing and expanding, the following are some of the different type of middleware in the market:

Transactional middleware

Transaction is an operation once triggered must be completed or not done at all (atomicity) keeping the data always consistent. It cannot be completed fully or if a problem occurs it must be totally remove leaving no trace of its existence.

Transactional middleware supports the development of systems involving transactions running across multiple different hosts. Transactional middleware supports both synchronous and asynchronous communication between hosts.

Message-oriented middleware

Messages are small pieces of information sent between sender and receiver. Message queue means message are sent and store into something like a “mailbox” then the receiver can collect it later. Group messaging uses this feature.

Message-oriented middleware uses many middleware to exchange message. Most message-oriented middleware provides an asynchronous communication service using message queues.

The advantage of using middleware is that it allows features like fault tolerance, priority schemes and client-server decoupling, etc. For example client server decoupling means that systems built with message-oriented middleware becomes very scalable.

Publish-subscribe system is a type of message-oriented middleware that implement a content-based network.

Procedural middleware

Many operating systems use this procedural middleware and usually used to provide Remote Procedure Calls (RPC). A Remote Procedure Call is when a sender’s computer can call a

75/117

Page 76: Network programing

Chapter 9-Middleware

function that is found in the sender machine or the receiver’s machine. The good thing is that the sender can run the function in the sender’s computer or the receiver’s computer.

RPC allow server components to be defined using an Interface Definition Language (IDL). From the IDL, it is possible to compile client and server stubs, which then perform the marshalling and un-marshalling and network communication.

RPC makes cross-platform distributed system programming very easy making this the most popular middleware.

Object middleware is just procedural middleware with Object oriented features such as inheritance, object references and exceptions. Examples of Object middleware are OMG’s CORBA, Microsoft COM, Java, RMI and Enterprise Java Beans.

76/117

Page 77: Network programing

Chapter 9-Middleware

Example of CORBA using Java

1. Create a folder call CORBA and go into that folder. Assuming Drive D (D:)

2. Enter the command prompt and go to CORBA folder.

3. Create a file call “Hello.idl” (this is our IDL file- interface file) in CORBA folder

module HelloApp{ interface Hello { string sayHello(); };};

4. In the command prompt type:D:\CORBA>idlj -fall -oldImplBase Hello.idl

The IDL compiler will create a folder call HelloApp and generate the following files inside it. Do not change the generate files.

Filename Class Type Description

Hello.javaInterface the "signature" file that implements the

hello contract

HelloHolder.java final class the instance "holder"

HelloHelper.javaAbstract provides functions for casting

references to their types

_HelloStub.java Normal the client stub

HelloOperations.java Interface the operations specific to hello

_HelloImplBase.java(HelloPOA.java)

Abstract the server skeleton(After JDK1.4 POA is generated)

The programmer only needs to focus on one (1) file: HelloOperations.java. This is the interface describing the methods that you must implement.

Now you will need to create two (2) java files call HelloServer.java and HelloClient.java.

The HelloServer.java file will contain HelloServant class and HelloServer class.

The HelloClient.java file will contain only HelloClient class.

77/117

Page 78: Network programing

Chapter 9-Middleware

5. After coding the two (2) java files as given compile both classes. When you compile HelloServer class, all the java files in HelloApp folder will also be compiled.

78/117

Page 79: Network programing

Chapter 9-Middleware

6. Now to code the HelloServer class.

import HelloApp.*;import org.omg.CosNaming.*;import org.omg.CosNaming.NamingContextPackage.*;import org.omg.CORBA.*;class HelloServant extends _HelloImplBase{ public String sayHello(){ return "\nHello world !!\n"; }}public class HelloServer { public static void main(String args[]){ try{ ORB orb = ORB.init(args, null); org.omg.CORBA.Object objRef; NamingContext ncRef; HelloServant helloRef = new HelloServant(); NameComponent nc = new NameComponent("Hello", ""); orb.connect(helloRef); objRef = orb.resolve_initial_references("NameService"); ncRef = NamingContextHelper.narrow(objRef); NameComponent path[] = {nc}; ncRef.rebind(path, helloRef);

java.lang.Object sync = new java.lang.Object(); synchronized (sync){sync.wait();} } catch (Exception e) { System.err.println("ERROR: " + e); e.printStackTrace(System.out); } }}

7. Now to code the HelloClient class

import HelloApp.*;import org.omg.CosNaming.*;import org.omg.CORBA.*;public class HelloClient{ public static void main(String args[]){ try{

ORB orb = ORB.init(args, null); org.omg.CORBA.Object objRef; NamingContext ncRef;

79/117

Page 80: Network programing

Chapter 9-Middleware

NameComponent nc = new NameComponent("Hello", ""); NameComponent path[] = {nc}; objRef = orb.resolve_initial_references("NameService"); ncRef = NamingContextHelper.narrow(objRef); Hello helloRef = HelloHelper.narrow(ncRef.resolve(path)); String hello = helloRef.sayHello(); System.out.println(hello); } catch (Exception e) { System.out.println("ERROR : " + e) ; e.printStackTrace(System.out); } }}

8. Remember to compile both HelloServer.java and HelloClient.java

9. Now to start the CORBA Naming Service. In the command prompt type:

D:\CORBA>start tnameserv -ORBInitialPort 1050

A new command screen popup with the following result. Leave this running.

Initial Naming Context:IOR:000000000000002b49444c3a6f6d672e6f72672f436f734e616d696e672f4e616d696e67436f 6e746578744578743a312e30000000000001000000000 000009e000102000000000f3139322e3136 382e31312e3234350000270f000 000000045afabcb0000000020000f424000000001000000000000000200000008526f6f74504f41000000000d544e616d65536572766963650000000000000008000000010000000114000000000000020000000100000020000000000001000100000002050100010001002000010109000000010001010000000026000000020002 TransientNameServer: setting port for initial object references to: 9999 Ready.

10. Now to run server class. Create a new command prompt interface.In the command prompt type:D:\CORBA> java HelloServer -ORBInitialPort 1050

80/117

Page 81: Network programing

Chapter 9-Middleware

11. Now to run the client. Create a new command prompt interface.In the command prompt type:D:\CORBA> java HelloClient -ORBInitialHost localhost -ORBInitialPort 1050

If the server is running in a different machine just change the localhost to the server’s IP address.

->

81/117

Page 82: Network programing
Page 83: Network programing

Chapter 10-TCP/IP

Chapter 10TCP/IP Programming

1. IP2. Hostname3. Service / Port Number4. Socket5. TCP6. UDP7. Blocking vs. Non-Blocking Sockets

83/117

Page 84: Network programing

Chapter 10-TCP/IP

Computer A Computer B

Software Software

Hardware Hardware

media

When “Computer A” wishes to talk to “Computer B”, Information must travel through several components (Software and Hardware) from “Computer A” down to the media and up to “Computer B”.

Software components like Email Application, Operating System, etc. Hardware components for example; the network interface card (NIC), the physical connection, etc.

Regardless of hardware or software the components must obey a standard protocol which defines the rules and parameters of how they should communication between each other. One of the most popular protocols is TCP/IP.

TCP/IP Layers

As previously taught, TCP/IP (Transmission Control Protocol/Internet Protocol) has only four (4) layers;

Application Layer (process-to-process): User interacts with the applications layers to connect to the network. Each application will have their individual protocol.

Transport Layer (host-to-host): The Transport Layer controls the main connection between the sender and the receiver. There is a standard way of communication regardless of the different type of network.

There are two main protocols at this layer; TCP (Transmission Control Protocol) or UDP (User Datagram Protocol). This will be discussed in detail later.

Internet Layer (internetworking): The Internet Layer has handles all the node to node communication, such as IP address, router, etc. Management of each node from the sender to the receiver is handled here.

Link Layer: The Link Layer handles all the physical management of the network from buffering to translation of data to binary format to prepare for selected media like twisted cable, coaxial cable, fiber optic, etc.

84/117

Page 85: Network programing

Chapter 10-TCP/IP

For application from “Computer A” to send and receive data with an application in “Computer B” via TCP/IP it must have several pieces of information.

1. IP (Internet Protocol).

Each computer or network devices system is assigned a unique 32-bit number which can be used to identify that particular computer or device over the network. This is known as the dotted quote a.k.a. dot-notation a.k.a. IP address.

The IP address is broken into four 8-bit numbers separated by periods looks something like "192.43.19.64".

Parts of the address are used to identify the network that the system is connected to, and the remainder identifies the system itself.

There are briefly Three (3) "classes" of addresses, referred to as "A", "B" and "C". The rule of thumb is that class "A" addresses are assigned to very large networks, class "B" addresses are assigned to medium sized networks, and class "C" addresses are assigned to smaller networks (networks with around 250 devices).

2. Hostnames

People do not like to remember numbers, as such the 32-bit number IP address as explain above it is typically expressed in either dot-notation or by a logical name called a hostname.

Just like IP address hostnames are also divided into several pieces separated by periods, called domains. Domains are hierarchical, with the top-level domains defining the type of organization that network belongs to, with sub-domains further identifying the specific network.

The fully qualified domain name is specified by naming the host and each parent sub-domain above it, separating them with periods.

The top-level domains are:gov government agenciescom commercial organizationsedu educational institutionsnet Internet service providersetc…

For example: jupiter.catalyst.com

The fully qualified domain name would be "jupiter.catalyst.com".

The system "jupiter" is part of the "catalyst" domain (a company’s local network) which in turn is part of the "com" domain (a domain used by all commercial enterprises).

85/117

Page 86: Network programing

Chapter 10-TCP/IP

86/117

Page 87: Network programing

Chapter 10-TCP/IP

In order to use the hostname instead of a IP address to identify a specific system or network, there must be some correlation between the two.

This is accomplished by one of two means: A local host table A name server. Domain Name System (DNS)

A host table is a text file that lists the IP address of a host, followed by the names that it’s known by. Typically this file is named hosts and is found in the same directory in which the software has been installed. Usually place in every computer all over the network.

A name server is a system called the DNS (actually, a program running on a system) which can be presented with a hostname and will return that host’s IP address. This approach is advantageous because the host information for the entire network is maintained in one centralized location, rather than being scattered about on every host on the network.

3. Service Ports (Port number)

Beside the IP address or Hostname, an application also needs to know how to address and connect to the specific program that it wishes to communicate with. This is accomplished by specifying a service port, a 16-bit number that uniquely identifies an application running on the system.

It is important note that a port number is use to address an application running on a computer BUT port number is fix by the individual operating system for each machine.

Therefore port number 101 for “Computer A” may be for Application ABC and port number 101 for ”Computer B” may be use for Application XYZ. Therefore there is no guarantee that the port number used in one machine is going to be the same port number used in another machine thus that port number may not be available in any of the machine.

Again people do not like numbers and therefore and instead of using numbers, a service names can be used. Just like the DNS, there is a local file call services that correlate all the service names to port numbers. This file lists the logical service name, followed by the port number and protocol used by the server.

4. Sockets

After knowing having the IP address (or Domain name) and port number (service name) next is to create what is called a socket. A socket is a communications end-point between two computer; “computer A” and “computer B”. Think of a telephone.

87/117

Page 88: Network programing

Chapter 10-TCP/IP

Creating a socket is just like having a telephone with a good dial tone. Establish a connection with the other program is like you dialing a telephone number.

You need to know the remote telephone number. For the socket example this telephone number (address) consists of three (3) key parts: the protocol family, Internet Protocol (IP) address and the service port number.

Family protocol is a number which is used to logically designate the group that a given protocol belongs to. The default family protocol in socket is the Internet Protocol family.

The socket interface has the ability to used many different protocols as such the protocol family tells the underlying network software which protocol is being used by the socket.

Socket are connected and data are sent from sender to receiver

RAW IP Datagram

Remember that the internet is a collection of networks, combined into a single, virtual network. The Internet Protocol provides the means by which any device on any network can communicate as if they were on the same physical network.

“Computer A” sends data over the network using the IP, the data it is sent in discrete units called “datagrams” a.k.a. packets. Please do not confuse raw IP datagram with User Datagram Protocol. They are different.

Raw IP datagram uses packet switching. There is no guarantee that a packet just like a envelope will actually reach the destination. The package may be lost, duplicated or delivered out of order during their travels over the network.

TCP (Transmission Control Protocol)

There is a need to have a more reliable, straight-forward way to exchange data without having to worry about lost packets or jumbled data, thus the Transmission Control Protocol (TCP) was developed. Thus TCP like datagram uses the IP but it offers a reliable, full-duplex byte stream which may be read and written just like reading and writing a file. All the features such as generating checksums, acknowledging the receipt of packets, retransmitting lost packets and so on are built in to the TCP package.

TCP is known as a connection-oriented protocol (circuit switching). Both “Computer A” and “Computer B” must establish a "connection" with each other before transmission of packet. “Computer B” must assume the role of the client, and the “Computer A” the server.

88/117

Page 89: Network programing

Chapter 10-TCP/IP

The client starts the connection, while the server waits, listen and respond to incoming connections. Once the connection is done, both sides may send and receive data until the connection is closed.

In TCP the connection uses a three-way handshake in which both sides exchange packets and establish the initial packet sequence numbers (this number is used to ensure that data is received in the order that it was sent).

89/117

Page 90: Network programing

Chapter 10-TCP/IP

TCP Frame Structure

TCP Client Code

import java.io.*;import java.net.*;public class Client{ Socket s = null; ObjectOutputStream out = null; public Client(){ try{ s = new Socket("localhost",2004); out = new ObjectOutputStream(s.getOutputStream()); out.flush(); out.writeObject("Hello there"); out.flush(); }catch(Exception ex){} finally{ try{ if (out != null) out.close(); if (s != null) s.close(); }catch(Exception ex){} } } public static void main(String x[]){Client c = new Client();}

90/117

Page 91: Network programing

Chapter 10-TCP/IP

}

91/117

Page 92: Network programing

Chapter 10-TCP/IP

TCP Server Code

import java.io.*;import java.net.*;public class Server{ ServerSocket ss= null; Socket s = null; ObjectInputStream in= null; public Server(){ try{ ss = new ServerSocket(2004,10); s = ss.accept(); in = new ObjectInputStream(s.getInputStream()); String message = (String)in.readObject(); System.out.println(message); } catch(Exception ex){} finally{ try{ in.close(); ss.close(); }catch(Exception ex){} } } public static void main(String x[]){Server svr = new Server();}}

UDP (User Datagram Protocol)

Again please do not confuse raw IP datagram with User Datagram Protocol.

User Datagram Protocol (UDP) does not present data as a stream of bytes and it does not it require an established a connection (packet switching) with another program in order to exchange information. Just like raw datagram, UDP also uses datagrams but with an additional port numbers and an optional checksum. Just like raw datagram, UDP there is no way to guarantee that data arrived at its destination.

Application that uses just focus on their work and let TCP handle all the acknowledgment and checking since these features are built into the packet. But application that uses UDP must implement their own acknowledgment and checking.

The main advantage of UDP over TCP is: speed and packet overhead.

TCP is a reliable protocol and it goes through great lengths to insure that data arrives at it’s destination intact, and as a result it exchanges a fairly high number of packets over the network.

92/117

Page 93: Network programing

Chapter 10-TCP/IP

UDP is an unreliable protocol thus it doesn’t have this overhead, and is considerably faster than TCP.

In those situations where speed is paramount, or the number of packets sent over the network must be kept to a minimum, UDP is the solution.

UDP Frame Structure

UDP Client Code

import java.net.*;import java.io.*;class Client{ DatagramSocket ds = null; DatagramPacket dp = null; public Client(){ try{ byte b[] = new byte[1024]; String str1 = "Hello There."; b = str1.getBytes(); dp = new DatagramPacket(b,0,b.length); dp.setAddress(InetAddress.getByName("localhost")); dp.setPort(5000); ds = new DatagramSocket(5001); ds.send(dp); ds.close(); }catch(Exception ex){ System.out.println(ex.getMessage()); } } public static void main(String x[]){Client c = new Client();}}

93/117

Page 94: Network programing

Chapter 10-TCP/IP

UDP Server Code

import java.net.*;import java.io.*;class Server{ DatagramSocket ds = null; DatagramPacket dp = null; public Server(){ try{ byte b[]=new byte[1024]; dp=new DatagramPacket(b,1024); ds=new DatagramSocket(5000); ds.receive(dp); String str = new String(dp.getData(),0,dp.getLength()); System.out.println(str); ds.close(); }catch(Exception ex){System.out.println(ex.getMessage());} } public static void main(String x[]){Server svr = new Server();}}

Client-Server Applications

All TCP programs use the client-server model.

The client application initiates what is called an active open. It creates a socket and actively attempts to connect to a server program.

The server application creates a “server socket” and passively listens for incoming connections from clients, performing what is called a passive open.

When the client initiates a connection, the server is notified that some process is attempting to connect with it. By accepting the connection, the server completes what is called a virtual circuit, a logical communications pathway between the two programs.

It’s important to note that the act of accepting a connection creates a new socket; the server socket continues to be used to listen for additional connections.

When the server no longer wishes to listen for connections, it closes the original passive socket.

There are five (5) significant steps that a TCP program must take to establish and complete a connection. The server side would follow these steps:

94/117

Page 95: Network programing

Chapter 10-TCP/IP

1. Create a socket.2. Listen for incoming connections from clients.3. Accept the client connection.4. Send and receive information.5. Close the socket when finished, terminating the conversation.

The client side will follow these steps:

1. Create a socket.2. Specify the address and service port of the server program.3. Establish the connection with the server.4. Send and receive information.5. Close the socket when finished, terminating the conversation.

Blocking vs. Non-Blocking Sockets

Normally once a server socket is connected to a client socket, the data is transfer and then immediately closed, the control is then return to the application for the next action. Occasionally the server and client socket connection may not be able to complete immediately and return control back to your program. For example, a read on a socket cannot complete until some data has been sent by the remote client.

If the server receives a signal from the client but here is no data waiting to be read, two things can happen:

Blocking Sockets

Here the function will wait until some data has been written on the socket thus the program is "blocked" until the request for data has been satisfied. Only when the remote system does write some data on the socket, the read operation will complete and execution of the program will resume. TCP/IP socket uses this by default.

Non-Blocking Sockets

Here the function sends an error message and immediately return to the application.The application must be able to recognize the error condition and handle the situation appropriately.

Programs that use non-blocking sockets can use one of two methods when sending and receiving data.

1. The first method, called polling, is when the program periodically attempts to read or write data from the socket (typically using a timer).

2. The second, and preferred method, is to use what is called asynchronous notification. This means that the

95/117

Page 96: Network programing

Chapter 10-TCP/IP

program is notified whenever a socket event takes place, and in turn can respond to that event. For example, if the remote program writes some data to the socket, a "read event" is generated so that program knows it can read the data from the socket at that point.

When an application uses a combination of blocking and non-blocking socket operations this will give the application the ability to switch between blocking and non-blocking modes "on the fly" provides a powerful and convenient way to perform socket operations.

->

96/117

Page 97: Network programing
Page 98: Network programing

Chapter 11-Nework Simulation & Modeling

Chapter 11Network Modeling and Simulation

1. Simulation2. How do we simulate 3. When do we do simulation 4. Network Simulation5. Purpose of Network simulators

98/117

Page 99: Network programing

Chapter 11-Nework Simulation & Modeling

Simulation

Simulation is a technique where a model of the real system is created by either:

1. Non Mathematical Simulation:

First analyze and capture information from a real life system (normally diagrams with symbols are used to represent the findings) then play back the observations from a production network.

2. Mathematical Simulation:

Using mathematical formulas to calculate the interaction between the different network entities (hosts/routers, data links, packets, etc)

The main objective of simulation is to study a system performance or operation and try to improve it. You will only be able to make a good prediction of any outcome if you understand how the system works.

The advantage of simulation is the ability to test out the network and its surrounding effects in a controlled manner to assess how the system would behave under different conditions without the risk of implementing in an actual system thus reducing the cost and risk.

The disadvantage of simulation is that no simulator that will ever be able to predict all the possible effects and outcome for all the given scenarios because no simulator can contain all the possible attributes.

How do we simulate? (Migrating from real world into a simulation)

Every real world system consists of elements and attributes that exists within a given boundary and is governed by rule and policies that will determine its behavior.

If the system exists then simulation will be made easier. The observer will spend time and resources studying the system, collecting as many surrounding element or attributes as possible inside the system.

Then the observer will try to understand how every element or attributes are related to each other.

99/117

Page 100: Network programing

Chapter 11-Nework Simulation & Modeling

If the system does not exist then simulation is be a lot harder as the observer will have to guess all the possible elements and attributes and form the relationship.

From the study the observer will be able to abstract relevant elements or attributes in the system predict the possible outcome given a certain scenario.

The observer will then be able to use a computer program to simulate the elements and attributes and their relationship. From here the observer can add in any pseudo random input into the environment and see the computer calculate out the possible prediction.

When do we do simulation?

1. If the system does not exist meaning the real-system is not available then the only way to be able to test out the performance of a system will be to simulate it.

2. If the system exists but if system is far to complex and costly or dangerous to be tested directly then simulation is use instead.

3. If we need to propose alternative solutions to a problem, we will need to simulation the system to test out the different scenario to get the different solutions or fine tune a solution.

4. Most prediction is base on mathematical approach, sometime the scenario is so complex that it becomes impossible to create a mathematical approach; as such a non mathematical simulation needs to be created.

Network Simulation

Network Simulation is a technique where a model of the real network is created by to show what will probably happen to:

1. The network 2. The application in the network and 3. The services used in that network under a given situation.

Thus the simulation is use as an analytical tool to predict and test out any “if else” environment.

Purpose of Network simulators:

1. Save cost and reduce risk

100/117

Page 101: Network programing

Chapter 11-Nework Simulation & Modeling

It is very expensive and time consuming to set up an entire test bed containing multiple networked computers, routers and data links. A network simulator makes this relatively fast and inexpensive.

Network engineers can experiment difficult or expensive or risky scenarios that might be particularly difficult or expensive to emulate using real hardware or software, for example testing a new network protocol.

2. Designing new network product or protocols

Network simulators are used by researchers, developers and engineers to design various kinds of networks, simulate and then analyze the effect of various parameters on the network performance.

A typical network simulator contains a wide range of “simulated” elements:

1. Networking technologies (WAN technologies: TCP, ATM, IP, etc and LAN technologies: Ethernet, Token rings, etc)

2. Network devices (computers, hubs, bridges, routers, switches, links, mobile units, etc)

3. Network application (Inventory Intranet system connecting to Customize Mobile )

The designer can easily build a simple or a complex networks by using all this “simulated” components.

3. Predict network performance and traffic.

All a network simulator beside representation of a network topology, network devices, link or media between those devices, they will also have way to represent the traffic between the nodes or even the type of protocol used to monitor and control the traffic. Some graphical applications allow users to easily visualize the workings of their simulated environment. Text-based applications are less intuitive but the users can customize more things.

Network emulation

Network emulation happens when a program is used to simulation live applications and services in order to observe end-to-end performance to the user desktop.

101/117

Page 102: Network programing

Chapter 11-Nework Simulation & Modeling

->

102/117

Page 103: Network programing

Chapter 12Kernel Programming

1. Operating System2. Division of Operating System3. Monolithic kernels4. Micro kernels

Page 104: Network programing

Chapter 12-Kernel Programming

Revising Operating System (OS)

Operating System

A computer can be divided into 2 main sections; the hardware and the software. The user interacts with the application software (or any other software) which in turn interacts with the operating system and using the BIOS the operating system will interact with the hardware.

Software

UserApplication Software

UtilitySoftware

EntertainmentSoftware

Etc

Operating System

BIOS

Hardware Machine

An OS is set of software that performs the following roles; Process Management, Input and Output Management, Storage Management, Networking and Security.

An operating system can be further divided into four (4) main sections;

OSOS ApplicationKernelAssembler (Drivers)Firmware (BIOS)

Hardware Machine

1. Operating System applications

The operating system normally made of many small individual software that does a specific task.

2. Kernel

The kernel (a.k.a. nucleus a.k.a. core) is simply the name given to the lowest level of abstraction that is implemented in software in this case the operating system.

3. Assembler (Drivers)

104/117

Page 105: Network programing

Chapter 12-Kernel Programming

Assembler: is a utility program used to translate assembly language statements into the target binary machine instructions and data (the code). Here all instructions are very machine dependent.

4. Firmware

Firmware usually refers to a fixed small program and/or data structure that is burn into a chip placed in any electronic device.

Kernel Programming

Kernel Programming is basically creating software not using any high level (3G) or 4G languages but using the operating system kernel itself.

Every operating system is different and uses a different kernel structure. In this guide book the student will be programming in a Windows Kernel.

Kernel Programming is the most complex and difficult tasks in software programming because it is place in the central of the operating system.

Effectiveness and efficiency in the design and implementation is very important to guarantee good performance.

Kernel software must be standalone and it cannot use other kernel software to ease the development because it might not remain in memory.

Kernel software are usually created to handle thread processing; low-level process scheduling (dispatching), inter-process communication, process synchronization, context switching, manipulation of process control blocks, interrupt handling, process creation and destruction, and process suspension and resumption.

There are basically two (2) type of kernel:

Monolithic kernels (obsolete)

In a monolithic kernel it uses one system call will have all and every OS services run and stay in the same memory making it big bulky software with the ability to do everything.

The two (2) advantages are; monolithic is easier to creates and provides a rich and powerful hardware access.

105/117

Page 106: Network programing

Chapter 12-Kernel Programming

The two (2) disadvantages of monolithic kernels is that it depends a lot on system components (a bug in a device driver might crash the entire system) and the large kernels are very difficult to maintain.

Micro kernels

The micro kernel approach breaks the task into different system call. Basic minimal OS services such as memory management, multitasking, and inter-process communication are place in small and minimal separate system call and the rest of the services depends on the hardware firmware, other services normally provided by the kernel are implemented in user-space programs (the servers).

The two (2) advantages of Micro kernels are; it is easier to maintain and allows normal higher level language to run some of the OS task. Thus there can be many different OS running on the same kernel thus it possible to dynamically switch among operating systems and to have more than one active simultaneously

The disadvantages of Micro kernels is that so many number of system calls and context switches might slow down the system because they typically generate more overhead than plain function calls.

How to create a batch file in Windows

Step 1 Switch on a windows machineStep 2 Open up the shell (command) interfaceStep 3 Open up a shell editor or text processor (NOT WORD PROCESSOR)Step 4 Type the following script:

@echo off cls echo "Good morning, world."

Step 5 Save the script into a filename – WinBatch.batStep 6 in the shell (command) interface type the following: WinBatch.batStep 7 Done

How to create a Windows script (Windows Scripting File with WSH)

Need to have:WSH is an environment for hosting either scripts; Jscript or VBscript

106/117

Page 107: Network programing

Chapter 12-Kernel Programming

WScript is use to run your script in the desktop environment for WSHCScript is use to run your script in the command environment for WSH

In other words: Cscript and Wscript are the two script hosts within the WSH

environment.

Step 1 Switch on a windows machineStep 2 Open up the shell (command) interfaceStep 3 Open up a shell editor or text processor (NOT WORD PROCESSOR)Step 4 Type the following script:

WSH.Echo( "Hello World" ); WSH.Quit( );

Step 5 Save the script into a filename – test.jsStep 6 in the shell (command) interface type the following:

WScript.exe test.js – will do a popup CScript.exe test.js – will appear in a command

prompt. test.js Here the WSH will use the default (WScript or CScript)

Step 7 Done

->

107/117

Page 108: Network programing

Chapter 13Network Management

1. Up-Time2. Down-Time3. FCAPS

Page 109: Network programing

Chapter 13-Network Management

Network management

There are two important words to remember in network management.

Uptime means the time the network is up and running starting from the last time the network was setup or was down. The goal of network management is to keep this state up as long as possible. The ideal situation will be to have 100% up time.

Downtime means the time the network is not running or when a particular service in a network cannot be performs. The ideal situation will be to have 0% down time but this is impossible for some network has to be shutdown for maintenance or upgrade.

Network management functions are divided into five (5) stages:F — FaultC — ConfigurationA — Accounting/AdministrationP — PerformanceS — Security

Fault management (Contingencies)

Fault management has two main tasks;

1. To diagnose and run corrective maintenance.

2. To study and prepare preventive and adaptive maintenance.

When a fault occurs, the user will immediately inform the network team either via telephone, email, newsgroup, etc. Immediately the network team will start to collect data to diagnose the source of the problem, all this will be updated in a log file. The team will then try to solve the problem immediately. Then the solution will also be logged in the log file.

After having a good record of fault logs it can be compile in a statistics to know the service provided by an individual network elements or a sub-networks or the whole network. From here decision can be made to change or upgrade a device.

Configuration management

The goals of configuration management include:

1. To collect and document as much information as possible on the current network, including the computers, devices, network setup, etc.

109/117

Page 110: Network programing

Chapter 13-Network Management

2. To keep track and update all changes to the documentation.

Good configuration management ensures that the network is properly documented and audited thus the other management task becomes very easy Fault management can easily diagnose the network. Accounting / Administration can easily track the resources and its performance. Security can easily setup contingency plans.Accounting a.k.a. Billing / Administration management

Accounting management has two main tasks;

1. To determine who is going to pay for the financial cost of an IT department.

2. To determine if the current IT department benefits worth the IT cost .

This depends on the way the IT Department is organized in relationship to the entire organization.

If the IT department is outsourced then this management (accounting/billing) needs to find a way to charge the user to pay for the IT facilities they are receiving.

If the IT department is an internal part of the organization, then this management (administration) needs to find a way to justify the cost that is incurred by the IT department.

Performance management

Performance management has two main tasks;

1. To study and improve the current performance and efficiency.

2. To study and prepare the network for the future performance.

The network performance is measured using the throughput, percentage utilization, error rates and response time. Collecting and analyzing all the performance data, the network health can be monitored and from there capacity or reliability issues can be fixed before they become a problem. An alarm can be use to trigger if the network performance drop to a certain level. Security management

110/117

Page 111: Network programing

Chapter 13-Network Management

Security management has two main tasks;

1. To study and setup current security.

2. To study and prepare for any form of contingency.

Security management setup up the username and password to control who is able to access the network. Security management also setup who can do what once they have accessed into the network. Security management will also find ways to secure all the software and data within a network.

In the event of a contingency the security management will be able to rebuild the entire network from scratch to a fully functional network.

->

111/117

Page 112: Network programing

Chapter 14Revision

Page 113: Network programing

Chapter 14-Revision

Answer all the question below in your own handwriting then submit your propose answer to your lecturer for assessment.

1. There are many client-server programming languages around; the most popular is PHP and HTML. Describe and relate PHP and HTML.

2. There are five (5) Internet Applications available. List and briefly describe each of the internet application.

3. Gone are the days when one computer can handle only one task at any given time. Nowadays computers have the capability to handle multi-threading and multi-programming. Clearly explain and relate multi-threading and multi-programming.

4. The Open System Interconnection (OSI) has become the benchmark for network protocols. Yet the OSI Layer itself consists of seven (7) different protocols. List and introduce either the top or bottom five (5) of the OSI Layer in their correct order?

5. Mr. Ali claims that XML will be able to take over the role of online database. Give a clear description of XML and Database and then show their relationship.

6. There are two type of switching; circuit and packet switching, and each of them has their own individual socket. With an example of how each of the sockets is applied, introduce and differentiate the stream and datagram socket.

7. There are three (3) network architectures; peer to peer, client-server and host and terminal, briefly describe each of the architectures. Explain if it is possible for one computer to be client and a server at the same time.

8. TCP/IP is known to be the main protocol used in the internet, but it is actually made out of two (2) separate protocols; TCP and IP. Describe TCP and IP separately and state which OSI layer they appear in.

9. Dotted quote and DNS have been use interchangeably but they are in fact two (2) totally separate elements. Describe and relate both these elements.

10. ServerSocket serverSocket = null; Socket clientSocket = null; try { serverSocket = new ServerSocket(4444);} catch

(IOException e) {}

113/117

Page 114: Network programing

Chapter 14-Revision

try { clientSocket = serverSocket.accept();} catch (IOException e) {}

Study the above Java code with socket and explain what it does.

11. Socket is a critical element used in client-server network programming. The server will use the socket connection differently from the client. Introduce the socket and explain how the server and the client use it to communicate.

12. Today mobile computing is the “in-thing” with many applications are available for it to implement. In the growth of mobile computing, middleware plays a very important role. Give a clear description and show the relationship between middleware and Mobile Computing.

13. Differentiate and explain the relationships between IP address, Sub Mask and DNS in a simple internetworking environment. Use suitable examples to support your answers.

14. A network manager needs to be able to manage a lot of factors such as setup, growth and security of a network. Point out five (5) ways to improve security for an email application either on the server or the client side? Use suitable examples to support your answers.

13.Socket s = new Socket("localhost", 2004);ObjectOutputStream out= null;out = new ObjectOutputStream(s.getOutputStream());out.flush();out.writeObject("Hello there");out.flush();

Study the above Java code and explain what it does. Also include in your answer the purpose of the Socket and ObjectOutputStream class.

14. WWW is a common internet application. Explain its nature using suitable example client scripting and server scripting.

15. Differentiate between internet, intranet and extranet. Use suitable examples to support your answers.

16.Windows IP ConfigurationHost Name . . . . . . . . . . . . : xyz123Primary Dns Suffix . . . . . :Node Type . . . . . . . . . . . . : UnknownIP Routing Enabled. . . . . . : No

114/117

Page 115: Network programing

Chapter 14-Revision

WINS Proxy Enabled. . . . : NoEthernet adapter BLABLABLA:Connection-specific DNS Suffix . :Description . . . . . .. . . . . : ABC Gigabit Ethernet ControllerPhysical Address. . . . . . : 70-5A-B6-17-71-B4Dhcp Enabled. . . .. . . . . : NoIP Address. . . . . . . . . . . : 192.168.11.254Subnet Mask . . . . . .. . . . : 255.255.255.0Default Gateway . . .. . . . : 192.168.33.10DNS Servers . . . . . . . . . : 202.133.99.11 202.133.99.12

The above is a simple “ipconfig” command given in a windows operating system. Briefly explain what ipconfig does then study the above information and carefully write two (2) positive and two (2) negative points on their network security.

17. Illustrate and discuss whether all the TCP/IP four (4) layers can be found in the seven OSI (7) layers.

18.ServerSocket ps = new ServerSocket(2004, 10);Socket s = ps.accept();ObjectInputStream in = null;in = new ObjectInputStream(s.getInputStream());System.out.println((String)in.readObject());

Study the above Java code and explain what it does. Also include in your answer the purpose of the Socket and ObjectInputStream class.

19. Middleware is becoming very popular now with the need for many applications to have portability and Interoperability. Justify how a web service in a three (3) tier programming structure acts as a middleware to encourage portability and interoperability.

20. One computer handling only one task is now replaced with computers having the capability to handle multi-threading and multi-programming. Differentiate between multi-threading and multi-programming. Use suitable examples to support your answers.

->

115/117

Page 116: Network programing

Reference:

To you, the student who is using this guide book.

Take note that I did not plagiaries any of the following online resources. I read the article, understood the contents and wrote it out in my own words. All the above knowledge and exercise are my own unless otherwise specified below.

References:

1. Operating system - Wikipedia, the free encyclopediaAvailable at http://en.wikipedia.org/wiki/Operating_system[Accessed: 14 March 2011]

2. Network topology- Wikipedia, the free encyclopediaAvailable at http://en.wikipedia.org/wiki/Network_topology[Accessed: 14 March 2011]

3. Physical vs. Logical Topologies By Giac.org [online] Available at http://www.giac.org/resources/whitepaper/network/32.php [Accessed 17 March 2011]

4. List of network protocols - Wikipedia, the free encyclopedia [online] Available at http://en.wikipedia.org/wiki/List_of_network_protocols [Accessed 17 March 2011]

5. Understanding Network Protocols by TopBits.com - [online] Available at http://www.tech-faq.com/understanding-network-protocols.html[Accessed 17 March 2011]

6. OSI model - Wikipedia, the free encyclopedia- [online] Available at http://en.wikipedia.org/wiki/OSI_model[Accessed 18 March 2011]

7. TCP/IP model - Wikipedia, the free encyclopedia- [online] Available at http://en.wikipedia.org/wiki/TCP/IP_model[Accessed 18 March 2011]

8. How to Install & Run Java | eHow.com - [online] Available at http://www.ehow.com/how_6693782_install-run-java.html# ixzz1HDt4TSJ0[Accessed 21 March 2011]

Page 117: Network programing

References

9. Multitasking, Multithreading, and Multiprocessing at National Instrument- [online] Available at http://zone.ni.com/reference/en-XX/help/371361B-01/lvconcepts/multitask_multithread_multip/[Accessed 23 March 2011]

10.Java Threads Tutorial by Java Threads Tutorial [online] Available at http://www.javabeginner.com/learn-java/java-threads-tutorial[Accessed 24 March 2011]

11.Concurrency control - Wikipedia, the free encyclopedia- [online] Available at http://en.wikipedia.org/wiki/Concurrency_control [Accessed 24 March 2011]

12."Synchronized" - How Java Supports Synchronization by herongyang.com- [online] Available at http://www.herongyang.com/Java/Synchronization-Support-in-Java-synchronized.html [Accessed 24 March 2011]

13.Java IDL: The "Hello World" Example- [online] Available at http://download.oracle.com/javase/1.3/docs/guide/idl/ jidlExample.html[Accessed 28 March 2011]

14.An Introduction to TCP/IP Programming With Socket Wrench by Catalyst Development Corporation- [online] Available at http://download.cnet.com/An-Introduction-to-TCP-IP-Programming/3000-2251_4-10042435.html [Accessed 30 March 2011]

15.Network management - Wikipedia, the free encyclopedia- [online] Available at http://en.wikipedia.org/wiki/Network_management [Accessed 4 April 2011]

http://www.ase.md/~aursu/ClientServerThreads.html

117/117