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

Network Programming in Java

This document provides an introduction and overview for programming networks using Java. It discusses Java development platforms and tools, basic Java network programming concepts like resolving hostnames and socket creation, sending and receiving data with both blocking and non-blocking methods, byte array operations, concurrency using threads, and some additional tips. The document aims to provide students with foundational knowledge on building networked applications in Java.

Uploaded by

tariq76
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
83 views

Network Programming in Java

This document provides an introduction and overview for programming networks using Java. It discusses Java development platforms and tools, basic Java network programming concepts like resolving hostnames and socket creation, sending and receiving data with both blocking and non-blocking methods, byte array operations, concurrency using threads, and some additional tips. The document aims to provide students with foundational knowledge on building networked applications in Java.

Uploaded by

tariq76
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

HELSINKI UNIVERSITY OF TECHNOLOGY Faculty of Electronics, Co unications an!

"uto ation

Introduction to Network Programming Using Java

# $%%& 'i((o Kiis(i

HELSINKI UNIVERSITY OF TECHNOLOGY Faculty of Electronics, Co unications an! "uto ation

Java starting point

Development platform

Unix/Linux/Windows available in t e department or computing center !ore information ttp"//www#tkk#fi/cc/computers/ Using $un JD% 'our program must run on desktop at !aari()

Deplo&ment platform

# $%%& 'i((o Kiis(i

HELSINKI UNIVERSITY OF TECHNOLOGY Faculty of Electronics, Co unications an! "uto ation

Java starting point *+,

Working wit development tools


Using ID- *-clipse. Net/eans. J0reator ###, Use existing libraries *)pac e 0ommons ###, Use of existing protocol implementations is forbidden )utomate compiling *)pac e )nt, and testing *JUnit, /ot programs are available in 1%% linux mac ines

1r& version control s&stems to s are &our code wit in &our group

ttp"//goblin#tkk#fi/c22/tutorials/svn# tml

# $%%& 'i((o Kiis(i

HELSINKI UNIVERSITY OF TECHNOLOGY Faculty of Electronics, Co unications an! "uto ation

Java starting point *3,

Information sources

1oda&4s slides and examples $un Java Documentation -xamples and tutorials available via searc engines $end mail to assistants *if ever&t ing else as failed,

# $%%& 'i((o Kiis(i

HELSINKI UNIVERSITY OF TECHNOLOGY Faculty of Electronics, Co unications an! "uto ation

/asic concepts

### concerning Java programming in general


-nvironment 5andling $treams 5andling 0 annels 5andling b&te arra&s 6esolving ostname 5andling address information 0reating $ockets $ending and receiving data using blocking / non(blocking met ods
,

### concerning network programming


# $%%& 'i((o Kiis(i

HELSINKI UNIVERSITY OF TECHNOLOGY Faculty of Electronics, Co unications an! "uto ation

Parse 0ommand Line in Java


public static void main(String[] args)
// String array containing the program arguments // Example iterating through array for (int i = 0 i ! args"length i##) $ String type = args[i##] String value = args[i] if(type"e%uals&gnore'ase(()l())$ // use value setExample*arameter( value ) + +

7r use t e existing packages like" ( )pac e 0ommons 0LI. see ttp"//commons#apac e#org/cli/

# $%%& 'i((o Kiis(i

HELSINKI UNIVERSITY OF TECHNOLOGY Faculty of Electronics, Co unications an! "uto ation

6esolve ostname

1ransform a s&mbolic name into a protocol(specific address $elect t e most suitable implementation for t e specific task Inet)ddress class for 3+(bit and 8+9(bit IP addresses used for unicast or multicast traffic Inet$ocket)ddress class is an implementation for t e IP address and port number pair used b& sockets for binding and connecting :ava#net#Inet)ddress :ava#net#Inet$ocket)ddress
.

)PI classes

# $%%& 'i((o Kiis(i

HELSINKI UNIVERSITY OF TECHNOLOGY Faculty of Electronics, Co unications an! "uto ation

$ocket 0reation *blocking,


,ava"net"Soc-et ,ava"net"ServerSoc-et ,ava"net".atagramSoc-et ,ava"net"/ulticastSoc-et

7pening a socket and using a stream for communication


java.net.Socket() 'reates an unconnected soc-et0 1ith the system)default type of Soc-et&mpl" java.net.Socket(InetAddress address, int port) 'reates a stream soc-et and connects it to the specified port number at the specified &* address" java.net.ServerSocket() 'reates an unbound server soc-et" java.net.ServerSocket(int port) 'reates a server soc-et0 bound to the specified port"
# $%%& 'i((o Kiis(i /

HELSINKI UNIVERSITY OF TECHNOLOGY Faculty of Electronics, Co unications an! "uto ation

$ocket 0reation *non(blocking,


,ava"nio"channels"Soc-et'hannel ,ava"nio"channels"ServerSoc-et'hannel

7pening a socket and using a c annel for communication


InetSocketAddress isa = new InetSocketAddress(targetAddrs, targetPort); // Connect SocketChannel sChannel = SocketChannel.open(); sChannel.con ig!re"locking( alse); #oolean connected = sChannel.connect(isa); i (connected == alse)$ sChannel. inishConnect(); %

# $%%& 'i((o Kiis(i

&

HELSINKI UNIVERSITY OF TECHNOLOGY Faculty of Electronics, Co unications an! "uto ation

$ending data *blocking,

0onnection(oriented *10P,

:ava#net#$ocket*Inet)ddress address. int port,


0reates a stream socket and connects it to t e specified port number at t e specified IP address# Write into 7utput$tream using suitable $tream writers

:ava#net#$ocket#get7utput$tream*,

# $%%& 'i((o Kiis(i

)%

HELSINKI UNIVERSITY OF TECHNOLOGY Faculty of Electronics, Co unications an! "uto ation

$ending data *blocking,

0onnectionless *UDP,

:ava#net#Datagram$ocket*int port,

0onstructs a datagram socket and binds it to t e specified port on t e local ost mac ine#

:ava#net#DatagramPacket*b&te;< buf. int lengt . Inet)ddress address. int port,

0onstructs a datagram packet for sending packets of lengt to t e specified port number on t e specified $ends a datagram packet from t is socket#

ost#

:ava#net#Datagram$ocket#send*DatagramPacket p,

# $%%& 'i((o Kiis(i

))

HELSINKI UNIVERSITY OF TECHNOLOGY Faculty of Electronics, Co unications an! "uto ation

6eceiving *blocking,

Data reception *10P, using a $ocket


Input$tream $ocket#getInput$tream*, 6ead Input$tream using suitable classes Datagram$ocket#receive*DatagramPacket pPacket, 6eceives a datagram packet from t is socket# 1 e DatagramPacket contains t e b&tes transmitted# 1o modif& socket be avior c eck t e setter met ods of t e specified implementation

Data reception *UDP, using a Datagram$ocket


# $%%& 'i((o Kiis(i

)$

HELSINKI UNIVERSITY OF TECHNOLOGY Faculty of Electronics, Co unications an! "uto ation

$ending data *non(blocking,


// // SocketChannel sChannel tr& $ String 'essage = (P) co!rse(; "&te"! er #! = "&te"! er.wrap( 'essage.get"&tes() ); sChannel.write(content); % catch (I*+,ception e) $ // -*)* A!to.generated catch #lock e.printStack-race(); %

# $%%& 'i((o Kiis(i

)*

HELSINKI UNIVERSITY OF TECHNOLOGY Faculty of Electronics, Co unications an! "uto ation

6eceiving data *non(blocking,


// // SocketChannel sChannel // Charset)ecoder decoder "&te"! er d#! = "&te"! er.allocate)irect(/012); Char"! er c# = n!ll; int readCo!nt = ./; tr& $ d#! .clear(); readCo!nt = sChannel.read(d#! ); d#! . lip(); c# = decoder.decode(d#! ); d#! . lip(); % catch (I*+,ception e) $ // -*)* A!to.generated catch #lock e.printStack-race(); %

# $%%& 'i((o Kiis(i

)+

HELSINKI UNIVERSITY OF TECHNOLOGY Faculty of Electronics, Co unications an! "uto ation

/&te arra& operations


Using b&te arra& or :ava#nio#/&te/uffer
// array operations byte[] array = ne1 byte[23] int array4ength = array"lenght byte[] content = ne1 byte[array4ength] System"arraycopy(array0 00 content0 00 array4ength) // 5yte5uffer String example = 67ello8 5yte5uffer buffer = 5yte5uffer"1rap( example"get5ytes() ) 5yte5uffer buffer9 = buffer"dublicate() buffer9"order( 5yte:rder"5&;<E=.&>=) byte[] array9 = buffer9"array()

7r use existing libraries like )pac e 0ommons I7 ttp"//commons#apac e#org/io/api(release/index# tml

# $%%& 'i((o Kiis(i

),

HELSINKI UNIVERSITY OF TECHNOLOGY Faculty of Electronics, Co unications an! "uto ation

0oncurrenc&
-vent /ased *$ingle 1 read 5andling man& connections,
See event #ased sol!tion ro' e,a'ples !sing java.nio.Channels

Using 1 reads
// // 3eceiver-hread i'ple'ents 3!nna#le inter ace 3eceiver-hread reveicerConnection = new 3eceiver-hread(); receiver = new -hread(reveicerConnection); receiver.start();

=or t e beginners read tutorials like ttp"//:ava#sun#com/docs/books/tutorial/essential/concurrenc&/ ttp"//:ava#sun#com/:+se/8#>#?/docs/guide/concurrenc&/index# tml ttp"//www#ibm#com/developerworks/edu/:(dw(:avat read(i# tml

# $%%& 'i((o Kiis(i

)-

HELSINKI UNIVERSITY OF TECHNOLOGY Faculty of Electronics, Co unications an! "uto ation

7t ers *8,

1r& to keep &our classes as simpl& as possible

group a certain set of functionalities into a specified class

Use design patterns to get a controlled structure for &our program

=or example 7bserver @ 7bservable pattern can be used to deliver t e received data for multiple users i#e# $erver must replicate data for multiple receivers"

$ocket container *source, implements 7bservable interface 0lient connection creates an instance of t e client container t at implements an 7bserver interface W en client container is created t e client observer is registered to t e observable source
).

# $%%& 'i((o Kiis(i

HELSINKI UNIVERSITY OF TECHNOLOGY Faculty of Electronics, Co unications an! "uto ation

7t ers *+,
6emember alwa&s to terminate program and release resources
-o handle sh!tdown signal !se addSh!tdown4ook() 'ethod or 3!nti'e class 3!nti'e.get3!nti'e().addSh!tdown4ook(new -hread() $ p!#lic void r!n() $ S&ste'.o!t.println ((Called at sh!tdown.(); % %); *ther alternative is to !se handle() 'ethod in s!n.'isc.Signal class to catch signals p!#lic static void 'ain(String56 args) throws +,ception $ Signal.handle(new Signal((I7-(), new Signal4andler () $ p!#lic void handle(Signal sig) $ S&ste'.o!t.println( (3eceived a interr!pt88(); % %); // %
# $%%& 'i((o Kiis(i )/

You might also like