You are on page 1of 18

Java network

programming (II)
A. Ngorora
• TCP is stream-based
• Stream-based: lossless communication
• We need IP address/domain name
• We need port number (> 1024)

Summary networking
basics 2
Network programming
• Ipconfig

• ping

Two NB DOS commands 3


Network programming
4
Network programming
5
Network programming
• Network running
• Create sockets
• Server listens
• Client tries to connect
• Communication via sockets – bytes

Summary: Java
networking 6
Network programming
• Could wrap bytes to have higher level data
representation
• (int/double/String…. or objects)
• Examples:
• DataInputStream
• DataInputStream
• BufferedReader
• PrintWriter

Wrapping the data 7


Network programming
• Start
• Server must be active (running)
• End?
• When one of the two programs end
• Keep running
while (true) in server program
{
}

Connections 8
Network programming
• Client and server on same computer
• Server and client on different computers
• Differentiate when creating Socket object:
• Localhost (same computer)
• host name (other)

Scenarios 9
Network programming
• BindException
• Attempting to create a server socket on a port
already in use
• UnknownHostException
• Host cannot be found
• ConnectionException
• Client program terminates

Important exceptions 10
Network programming
• Package: java.net

• Flush
• Clears the buffer for sending the data
through

Others important stuff 11


Network programming
• Server uses to obtain information about
• IP address
• Host name
• InetAdress inetAdress =
socket.getInetAddress();

InetAddress class 12
Network programming
• Use the inetAddress object to get the host
name/address
• Get host name
• inetAdress.getHostName()
• Get address
• inetAdress.getHostAddress()

Getting host
name/address 13
Network programming
• Multiple clients through threads
• Each client one thread
• while(true)
{
Socket socket = serverSocket.accept();
Thread thread = new ThreadClass (socket);
thread.start();
}

Servers for multiple


clients 14
Network programming
• Each iteration creates new connection
• New connection, new thread
• Thread: handles communication between
the server and the new client

While loop 15
Network programming
• Objects must be Serializable
• Class should thus have implements
Serializable
• readObject()
• writeObject()

Send and receive objects 16


Network programming
• Multiple clients can connect to a server (running)
• Threads are created for each client-server connection
• Data can be send on various levels (byte/data/objects)

Summary 17
Network programming
• Listing 33.4…. Change to create separate class for the
thread…..
• HOMEWORK: Exercise 33.9, 33.10 (will be done in
tutorial classes)

Practical 18
Network programming

You might also like