1 / 40

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

Java Networking TCP Yangjun Chen Dept. Business Computing University of Winnipeg. 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

henrik
Télécharger la présentation

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

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

  2. 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. Sever - client communication • A socket can be considered as a connection point. port1 portN SEVER: … ... Sockets(Ipc, Port’sM, port1) IP address IPs IP address IPc Socketc(Ips, Port1, port’M) … ... CLIENT: Port’1 Port’M

  4. 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. 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. 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. 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. 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. 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. 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. 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. 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. TCP • Java networking classes use TCP • java.net package provides the functionality for networking • - java.net • . URL() • . URLConnection() • . Socket() • . SocketServer()

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

  24. 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. 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 Instantiate the supporting classes

  26. 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. 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. 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. 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. 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. 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. 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;

  33. 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. 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. 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. 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. 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. 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. 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. Example: Receive Data(3) catch (java.io.IOException e) { system.out.println(e); System.exit(0); }//catch }//run }//RcveData

More Related