TCP - University of Winnipeg

Download Report

Transcript TCP - University of Winnipeg

Java Networking TCP
Yangjun Chen
Dept. Business Computing
University of Winnipeg
Jan. 2004
1
Ports
• 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.
Jan. 2004
2
Sever - client communication
• A socket can be considered as a connection point.
port1
SEVER:
portN
… ...
IP address
Sockets(Ipc, Port’sM, port1)
IP
s
IP address
Socketc(Ips, Port1, port’M)
CLIENT:
Port’1
Jan. 2004
Port’M
3
Ports
• 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.
Jan. 2004
4
Internet 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.
Jan. 2004
5
Internet 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()
Jan. 2004
6
Creating 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( )
Jan. 2004
7
Creating 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; i<addresses.length;i++)
System.out.println(addresses[i]);
}//try
catch (UnknownHostException e) {}
}//main
}//class
Jan. 2004
8
Creating 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
Jan. 2004
9
Parsing 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());
Jan. 2004
10
Parsing InetAddress
byte[] quad = me.getAddress();
for(int i = 0; i < quad.length; i++)
System.out.print(quad[i] + ”.”);
System.out.println();
}//try
catch (UnknownHostException e) {
( System.err.println(e);
}//catch
}//main
}//class
Jan. 2004
11
TCP
• 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.
Jan. 2004
12
TCP
• Java networking classes use TCP
• java.net package provides the functionality for networking
-
java.net
.
.
.
.
Jan. 2004
URL()
URLConnection()
Socket()
SocketServer()
13
Sockets
• 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.
Jan. 2004
14
Sockets
• 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
Jan. 2004
15
Establishing 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.
Jan. 2004
16
Sending/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
Jan. 2004
17
Closing 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()
Jan. 2004
18
Example: 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;
DataInputstream is = null;
DataInputStream stdIn = new DataInpuuStream(System.in);
Jan. 2004
19
Example: EchoTest(2)
try {
eSocket = new Socket(host,7);
os = new DataOutputStream(eSocket.getOutputStream());
is = new
DataTnputStream(eSocket.getInputStream()); }
//try
catch (UnknownHostException e) {
System.err.println(“Unknown host: "+host);
}//catch
catch (IOException e) {
System.err.println("No I/O connection to: “ + host);
}///catch
Jan. 2004
20
Example: EchoTest(3)
if (eSocket !=null && os!=null && is!=null) {
try {
String uTnput;
while ((uInput=stdIn.readLine()) != null) {
os.writeBytes(userlnput);
os.writeByte('\n');
System.out.println("echo:
+is.readLineo);
if (userInput.equals("quit”))
break;
}//while
os.close();
is.close();
Jan. 2004
21
Example: EchoTest(4)
eSocket.close();
}//try
catch (IOException e)
System.err.println("I/O failed on the connection to: “ + host);
}//catch
}//if
}//try
}//class
Jan. 2004
22
Example: 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
Jan. 2004
23
Example: Chat Client(2)
if (a.length > 1) {
port = Integer.parseInt(a[i]);
} //if
if (a.length > 0) {
host = a[0];
}//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
Jan. 2004
24
Example: Chat Client(3)
catch (java.net.ConnectException e){
System.out.println(e);
System.exit(0);
}//catch
SendData sd = new SendData(sock);
RcveData rd = new RcveData(sock);
sd.start();
rd.start();
}//main
}//chat_client
Jan. 2004
Instantiate the
supporting classes
25
Server 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.
Jan. 2004
26
Accepting 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.
Jan. 2004
27
Server 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.
Jan. 2004
28
Server Sockets:Queue
• 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.
Jan. 2004
29
Server Sockets:Queue
• 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.
Jan. 2004
30
Example: 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 {
Jan. 2004
31
Example: Chat Server(2)
public static void main(String a[]) {
int blog = 600;
int port = 9100;
Socket sock = null;
if (a.length > 0) {
port = Integer.parseInt(a[0]);
}//if
ServerSocket servsock - null;
Jan. 2004
32
Example: 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
Jan. 2004
33
Example: 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
Jan. 2004
34
Example: 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;
Jan. 2004
35
Example: Send Data(2)
try {
outputStreamWriter outw = new
outputStreamwriter(sock.getOutputStream());
BufferedWriter sockout=new BufferedWriter(outw);
TnputStreamReader inr = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(inr);
while ((line = in.readLine()) != null) {
sockout.write(line+"\n");
Jan. 2004
36
Example: Send Data(3)
sockout.flush();
yield();
}//while
}//try
catch (java.io.IOException e) {
System.out.println(e);
System.exit(0);
}//catch
}//run
}//SendData
Jan. 2004
37
Example: 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;
Jan. 2004
38
Example: 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
Jan. 2004
39
Example: Receive Data(3)
catch (java.io.IOException e) {
system.out.println(e);
System.exit(0);
}//catch
}//run
}//RcveData
Jan. 2004
40