Jan Java Networking TCP Yangjun Chen Dept. Business Computing University of Winnipeg
Jan 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 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)
Jan 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 Internet Addresses Every computer on the net has an associated four-byte IP address that is unique. Usually represented in dotted quad format like 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 or It's the numerical address that is fundamental, not the name. You can have multiple names that represent the same IP address.
Jan 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 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 Creating InetAddress Objects import java.net.*; class ibm{ public static void min (String args[]) { try ( InetAddress[] addresses = InetAddress.getAllEyName(" for (int i = 0; i<addresses.length;i++) System.out.println(addresses[i]); }//try catch (UnknownHostException e) {} }//main }//class
Jan 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 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 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 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 TCP Java networking classes use TCP java.net package provides the functionality for networking -java.net. URL(). URLConnection(). Socket(). SocketServer()
Jan 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 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 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 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 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 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 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 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 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 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
Jan 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 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
Jan 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 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 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 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 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 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 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;
Jan 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 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 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 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 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 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 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 Example: Receive Data(3) catch (java.io.IOException e) { system.out.println(e); System.exit(0); }//catch }//run }//RcveData