Presentation is loading. Please wait.

Presentation is loading. Please wait.

Jan. 20041 Java Networking TCP Yangjun Chen Dept. Business Computing University of Winnipeg.

Similar presentations


Presentation on theme: "Jan. 20041 Java Networking TCP Yangjun Chen Dept. Business Computing University of Winnipeg."— Presentation transcript:

1 Jan. 20041 Java Networking TCP Yangjun Chen Dept. Business Computing University of Winnipeg

2 Jan. 20042 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.

3 Jan. 20043 Sever - client communication A socket can be considered as a connection point. IP address port1 portN IP s …... IP c …... Port’1 Port’M IP address SEVER: CLIENT: Socket s (Ip c, Port’sM, port1) Socket c (Ip s, Port1, port’M)

4 Jan. 20044 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.

5 Jan. 20045 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.

6 Jan. 20046 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()

7 Jan. 20047 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( )

8 Jan. 20048 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

9 Jan. 20049 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

10 Jan. 200410 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());

11 Jan. 200411 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

12 Jan. 200412 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.

13 Jan. 200413 TCP Java networking classes use TCP java.net package provides the functionality for networking -java.net. URL(). URLConnection(). Socket(). SocketServer()

14 Jan. 200414 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.

15 Jan. 200415 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

16 Jan. 200416 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.

17 Jan. 200417 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

18 Jan. 200418 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()

19 Jan. 200419 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);

20 Jan. 200420 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

21 Jan. 200421 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();

22 Jan. 200422 Example: EchoTest(4) eSocket.close(); }//try catch (IOException e) System.err.println("I/O failed on the connection to: “ + host); }//catch }//if }//try }//class

23 Jan. 200423 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; Stringhost = “localhost"; intport9100; Declaring a Socket object

24 Jan. 200424 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

25 Jan. 200425 Example: Chat Client(3) catch (java.net.ConnectException e){ System.out.println(e); System.exit(0); }//catch SendDatasd = new SendData(sock); RcveData rd = new RcveData(sock); sd.start(); rd.start(); }//main }//chat_client Instantiate the supporting classes

26 Jan. 200426 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.

27 Jan. 200427 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.

28 Jan. 200428 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.

29 Jan. 200429 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.

30 Jan. 200430 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.

31 Jan. 200431 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 {

32 Jan. 200432 Example: Chat Server(2) public static void main(String a[]) { intblog = 600; intport = 9100; Socketsock = null; if (a.length > 0) { port = Integer.parseInt(a[0]); }//if ServerSocket servsock - null;

33 Jan. 200433 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

34 Jan. 200434 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

35 Jan. 200435 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;

36 Jan. 200436 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");

37 Jan. 200437 Example: Send Data(3) sockout.flush(); yield(); }//while }//try catch (java.io.IOException e) { System.out.println(e); System.exit(0); }//catch }//run }//SendData

38 Jan. 200438 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;

39 Jan. 200439 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

40 Jan. 200440 Example: Receive Data(3) catch (java.io.IOException e) { system.out.println(e); System.exit(0); }//catch }//run }//RcveData


Download ppt "Jan. 20041 Java Networking TCP Yangjun Chen Dept. Business Computing University of Winnipeg."

Similar presentations


Ads by Google