Title: Java%20Networking%20TCP
1Java Networking TCP Yangjun Chen Dept. Business
Computing University of Winnipeg
2Ports
- In general, computers only have one Internet
address, but computers usually need to
communicate with more than one host at a time. - Ports map incoming data to a particular
- process or application running on a computer,
- With every socket, there needs to be an
associated port number - Example - regular post. The IP address is like
the street address while the port number would
represent the house number.
3Sever - client communication
- A socket can be considered as a connection point.
port1
portN
SEVER
...
Sockets(Ipc, PortsM, port1)
IP address
IPs
IP address
IPc
Socketc(Ips, Port1, portM)
...
CLIENT
Port1
PortM
4Ports
- Ports can range in value from 1 to 65535, with
ports 1 to 1023 being reserved for root access in
Unix. - On Windows NT, 95 and Macs, any user can listen
on any port. - Only one program can listen on a given TCP port
at the same time. - However, many remote hosts can connect to the
same remote port.
5Internet Addresses
- Every computer on the net has an associated
four-byte IP address that is unique. Usually
represented in dotted quad format like
148.131.31.1. where each byte is an unsigned
value in the range of 0 to 255. - Since numbers are hard to remember, these numbers
are mapped into names like www.uwinnipeg.ca or
www.umanitoba.ca. - It's the numerical address that is fundamental,
not the name. You can have multiple names that
represent the same IP address.
6Internet Addresses
- java. net. InetAddress class are used to manage
such addresses. - Some are shown here -
- - InetAddress getByName(String host)
- - InetAddress getAllByName(String host)
- - InetAddress getLocalHost()
- - String getHostName()
- - byte getHostAddress()
- - boolean isMulticastAddress()
7Creating InetAddress Objects
- The InetAddress class is unusual in that it
doesn't have a public constructor, so to create
an object you would pass in the host - name or string format of the dotted quad address
into the static - method
-
- InetAddress.getByName( )
8Creating InetAddress Objects
import java.net. class ibm public
static void min (String args) try
( InetAddress addresses
InetAddress.getAllEyName("
www.ibm.com") for (int i 0
iltaddresses.lengthi) System.out.println(a
ddressesi) //try catch
(UnknownHostException e) //main //class
9Creating InetAddress Objects
- To create an InetAddress that refers to your own
machine use the static getLocalHost() method. - try
- InetAddress me InetAddress.getLocalHost( )
- //try
- catch (UnknownHostException e)
- System.err.println( )
- //catch
10Parsing InetAddress
- Given an InetAddress, we might want to know the
host name or it's IP address as a string or byte
array. - ImporL java.net.
- public class address
- public static void main(String args)
- try
- InetAddress me new netAddress.getLocalHost(
) System.out.println(me.getHostName())
System.out.println(me.getHostAddress())
11Parsing InetAddress
byte quad me.getAddress() for(int i
0 i lt quad.length i) System.out.print(q
uadi .) System.out.println() //t
ry catch (UnknownHostException e) (
System.err.println(e) //catch //main
//class
12TCP
- TCP (Transmission Control Protocol)
- - a connection-based protocol that provides a
reliable flow of data between two computers. - - It allows retransmission of lost data.
- - It provides multiple paths through different
routers in case one goes down. - - Bytes are delivered in the order they are
sent. - Applications using TCP to communicate
- - HTTP, FTP, Telnet, etc.
13TCP
- Java networking classes use TCP
- java.net package provides the functionality for
networking - - java.net
- . URL()
- . URLConnection()
- . Socket()
- . SocketServer()
14Sockets
- Host's native networking s/w handles the
splitting of data into packets on the
transmitting side of a connection, and the
reassembly of packets on the receiving side. - Java programmers are presented with a higher
level abstraction called a socket.
15Sockets
- A socket represents a reliable connection for
data transmission between two hosts. - Four fundamental operations
- - 1. Connect to a remote machine
- - 2. Send data
- - 3. Receive data
- - 4. Close the connection
16Establishing a Connection
- Accomplished through the class constructors
- - java.net.Socket()
- . client side implementation
- - java.net.ServerSocket()
- . server side implementation
- Each socket is associated with exactly one host.
- To connect to a different host, a new socket
object must be created.
17Sending/Receiving Data
- Sending and Receiving data is accomplished with
input and output streams. - - public InputStream getInputStream()
- - public OutputStream getOutputStream()
- - both of these classes throw an IOException
18Closing a Connection
- There's a method to close a socket.
- - public synchronized void close()
- - this method throws an IOException as well.
- For a well behaved program, we need to close the
I/O streams as well. - Close any streams connected to a socket before
closing the socket. - - OutStream.close()
- - InStream.close()
- - Socket.close()
19Example EchoTest(l)
import java.io. import java.net., public
class EchoTest public static void
main(String args) String
host"truffle" Socket eSocket
null DataoutputStream os null DataInputstr
eam is null DataInputStream stdIn new
DataInpuuStream(System.in)
20Example EchoTest(2)
try eSocket new Socket(host,7) os
new DataOutputStream(eSocket.getOutputStream())
is new DataTnputStream(eSocket.getInp
utStream()) //try catch (UnknownHostExcepti
on e) System.err.println(Unknown host
"host) //catch catch (IOException e)
System.err.println("No I/O connection to
host) ///catch
21Example EchoTest(3)
if (eSocket !null os!null is!null)
try String uTnput while
((uInputstdIn.readLine()) ! null)
os.writeBytes(userlnput) os.writeByte
('\n') System.out.println("echo i
s.readLineo) if (userInput.equals("quit))
break //while os.close() is
.close()
22Example EchoTest(4)
eSocket.close() //try catch
(IOException e) System.err.println("I/O
failed on the connection to host)
//catch //if //try //class
23Example Chat Client(l)
import java.io. import java.net. import
RcveData import SendData public class
chat_client extends Thread public static
void main(String a) throws IOException
Socket sock null String host
localhost" int port 9100
Declaring a Socket object
24Example Chat Client(2)
if (a.length gt 1) port Integer.parseInt(ai
) //if if (a.length gt 0) host
a0 //if System.out.println("using port
port connecting to host) try sock
new Socket(host,port) //try
Establish a connection to the specified bost and
port
25Example Chat Client(3)
catch (java.net.ConnectException e)
System.out.println(e) System.exit(0) //ca
tch SendData sd new SendData(sock) RcveData
rd new RcveData(sock) sd.start() rd.start()
//main //chat_client
Instantiate the supporting classes
26Server Sockets
- A host that responds to a connection.
- Instead of connecting to a remote host, a server
program will wait for others to connect to it.
27Accepting Connections
- 1) A server socket binds to a particular port.
- 2) It then listens for connection attempts.
- 3) When it detects an attempt, it will accept the
connection. - - public Socket accept() Throws IOException
- The accept () method blocks until a connection is
detected. - It returns a java. net. Socket Object that is
used to perform the communication.
28Server Sockets
- Multiple clients can connect to the same port on
a server at any time. - The data are distinguished by the port numbers
and the client addresses. - However, no more than one socket can listen to a
particular port at a time. - This is why servers tend to be heavily
multithreaded. - Generally, the server socket listening to the
port will accept connections and then pass the
actual processing to other threads.
29Server SocketsQueue
- Incoming connections are stored in a FIFO queue
until the server can accept them. - If the queue is full, then connection attempts
will be refused until space opens up. - The default queue length for most systems is
between 5 and 50.
30Server SocketsQueue
- The length of the queue can be adjusted by
passing in the size of the queue in the backlog"
parameter. - - public ServerSocket(int port,int backlog)
- Each system has a maximum queue length, so any
values for the queue length longer than the
maximum will be set to the maximum.
31Example Chat Server(l)
//This is a simple chat server written in
Java import java.io. import
java.net. import RcveData import
SendData public class chat_server extends
Thread
32Example Chat Server(2)
public static void main(String a)
int blog 600 int port
9100 Socket sock null if (a.length gt
0) port Integer.parseInt(a0) //if
ServerSocket servsock - null
33Example Chat Server(3)
System.out.println("using port port)
try servsock new Serversocket(port,blog
) // try catch (java.io.IOException e)
System.out.println(e) System.exit(0)
//catch try sock servsock.accept()
//try
34Example Chat Server(4)
catch (java.io.IOException e)
System.out.println(e) System.exit(0)
) //catch SendData Sd new
SendData(sock) RcveData rd new
RcveData(sock) sd.start() rd.start()
//main //class
35Example Send Data(1)
import java.net. import java.io. public
class SendData extends Thread Socket
sock public SendData(Socket sock)
this.sock sock //SendData
constructor public void run() String
line
36Example Send Data(2)
try outputStreamWriter outw
new outputStreamwriter(sock.getOutputStrea
m()) BufferedWriter sockoutnew
BufferedWriter(outw) TnputStreamReader inr
new InputStreamReader(System.in) BufferedRead
er in new BufferedReader(inr) while ((line
in.readLine()) ! null) sockout.write(lin
e"\n")
37Example Send Data(3)
sockout.flush() yield() //whi
le //try catch (java.io.IOException e)
System.out.println(e) System.exit(0)
//catch //run //SendData
38Example Receive Data(1)
import java.net. import java.io. public
class RcveData extends Thread Socket
sock public RcveData(Socket sock)
this.sock sock public void run()
String line
39Example Receive Data(2)
try InputStreamReader inr
new InputStreamReader(sock.getInputStream())
BufferedReader in new BufferedReader(inr)
while (line in.readLine( )) ! null)
System.out.print(Receiving
) System.out.println(line) yield() //
while //try
40Example Receive Data(3)
catch (java.io.IOException e)
system.out.println(e) System.exit(0)
//catch //run //RcveData