INDEX S.No. Title 1. Create a socket for HTTP for web-page upload and download. 2. Write a code simulating ARP/RARP protocols. 3. Study of TCP/UDP performance. 4. Performance comparison of MAC protocols. 5. Performance comparison of routing protocols. 6.(a) Write a program to implement echo server and client in java using TCP sockets. 6.(b) Write a program to implement data server and client in java using TCP sockets. 6.(c) Write a program to implement a chat server and client in java using TCP sockets. 7.(a) Write a program to implement echo server and client in java using UDP sockets. 7.(b) Write a program to implement DNS server and client in java using UDP sockets. 7.(c) Write a program to implement echo server and client in java using UDP sockets. 8. To implement simple calculator and invoke arithmetic operations from a remote client. 9. To implement bubble sort and sort data using a remote client. 10. To simulate a sliding window protocol that uses Go Back N ARQ. Remarks PRACTICAL-1 Aim: Create a socket for HTTP for web-page upload and download. Source Code: MyClient.java: import javax.swing.*; import java.net.*; import java.awt.image.*; import javax.imageio.*; import java.io.*; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; class MyClient { public static void main(String args[]) throws Exception { Socket s; BufferedImageimg = null; s=new Socket("localhost",90); System.out.println("****----Client Start Running----****"); try { System.out.println("Reading image from Disk..."); img = ImageIO.read(new File("mukand.jpg")); ByteArrayOutputStreamba = new ByteArrayOutputStream(); ImageIO.write(img, "jpg", ba); ba.flush(); byte[] b = ba.toByteArray(); ba.close(); System.out.println("Sending Image to Server..."); OutputStream o=s.getOutputStream(); DataOutputStream d = new DataOutputStream(o); d.writeInt(b.length); d.write(b, 0, b.length); System.out.println("Image sent to server"); d.close(); o.close(); }catch(Exception e) { System.out.println("Ouccering Exception is: e.getMessage()); s.close();} s.close(); } } MyServer.java: import java.net.*; import java.io.*; import java.awt.image.*; import javax.imageio.*; import javax.swing.*; class MyServer { public static void main(String args[]) throws Exception { ServerSocket h=new ServerSocket(90); " + System.out.println("****----Server Started----****"); System.out.println("Server Waiting for image...."); Socket s=h.accept(); System.out.println("Client connected With Server"); InputStream in =s.getInputStream(); DataInputStream dis = new DataInputStream(in); intlen = dis.readInt(); System.out.println("Image Size: " + len/1024 + "KB"); byte[] data = new byte[len]; dis.readFully(data); dis.close(); in.close(); InputStreamian = new ByteArrayInputStream(data); BufferedImagebImage = ImageIO.read(ian); JFrame f = new JFrame("Server"); ImageIcon icon = new ImageIcon(bImage); JLabel l = new JLabel(); l.setIcon(icon); f.add(l); f.setSize(400,400); f.setVisible(true); } } Output: MyClient.java: MyServer.java: PRACTICAL-2 Aim: Write a code simulating ARP/ RARP protocols. Source Code: import java.io.*; import java.util.*; class Arp_Rarp { private static final String Command = "arp -a"; public static void getARPTable(String cmd) { try{ File fp = new File("ARPTable.txt"); FileWriterfw = new FileWriter(fp); BufferedWriterbw = new BufferedWriter(fw); Process P = Runtime.getRuntime().exec(cmd); Scanner S =new Scanner (P.getInputStream()).useDelimiter("\\A"); while(S.hasNext()) bw.write(S.next()); bw.close(); fw.close(); }catch(Exception e) { System.out.println("Exception:="+e);} } public static void findMAC(String ip) { try{ File fp = new File("ARPTable.txt"); FileReaderfr = new FileReader(fp); BufferedReaderbr = new BufferedReader(fr); String line; while ((line = br.readLine()) != null) { if (line.contains(ip)) { System.out.println("Internet Address Physical Address System.out.println(line); break; } } if((line == null)) System.out.println("Not found"); fr.close(); br.close(); }catch(Exception e) { System.out.println("Exception:="+e);} } public static void findIP(String mac) throws Exception { try{ File fp = new File("ARPTable.txt"); FileReaderfr = new FileReader(fp); BufferedReaderbr = new BufferedReader(fr); String line; while ((line = br.readLine()) != null) { if (line.contains(mac)) { System.out.println("Internet Address Physical Address System.out.println(line); break; Type"); Type"); } } if((line == null)) System.out.println("Not found"); fr.close(); br.close(); }catch(Exception e) { System.out.println("Exception:="+e);} } public static void main(String... args) throws Exception { getARPTable(Command); Scanner S = new Scanner(System.in); System.out.println("ARP Protocol."); System.out.print("Enter IP Address: "); String IP = S.nextLine(); findMAC(IP); System.out.println("RARP Protocol."); System.out.print("Enter MAC Address: "); String MAC = S.nextLine(); findIP(MAC); } } Output: Arp_Rarp.java: PRACTICAL-3 Aim: Study of TCP/ UDP performance. Source Code: MyClient.java: import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.util.Scanner; class MyClient { public static void main(String args[]) throws IOException { System.out.println("Write Some msg for Server:-"); Scanner sc = new Scanner(System.in); DatagramSocket ds = new DatagramSocket(); InetAddressip = InetAddress.getLocalHost(); byte buf[] = null; while (true) { String inp = sc.nextLine(); buf = inp.getBytes(); DatagramPacketDpSend = new DatagramPacket(buf, buf.length, ip, 1234); ds.send(DpSend); if (inp.equals("bye")) break; } } } MyServer.java: import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; class MyServer { public static void main(String[] args) throws IOException { System.out.println("Server is waiting Client Msg:-"); DatagramSocket ds = new DatagramSocket(1234); byte[] receive = new byte[65535]; DatagramPacketDpReceive = null; while (true) { DpReceive = new DatagramPacket(receive, receive.length); ds.receive(DpReceive); System.out.println("Client:-" + data(receive)); if (data(receive).toString().equals("bye")) { System.out.println("Client sent bye....EXITING"); break; } receive = new byte[65535]; } } public static StringBuilder data(byte[] a) { if (a == null) return null; StringBuilder ret = new StringBuilder(); inti = 0; while (a[i] != 0) { ret.append((char) a[i]); i++; } return ret; } } Output: MyClient.java: MyServer.java: PRACTICAL-4 Aim: Performance comparison of MAC protocols. Theory: Media Access Control: ⦁ In a broadcast network, the single communication channel is to be allocated to one transmitting user at a time. ⦁ The other users connected to this medium should wait. ⦁ Datalink layer is divided into two functionality-oriented sublayers i.e Data Link Control and Media Access Control Sublayer. ⦁ The upper sublayer is basically responsible for the data link control, and the lower sublayer is responsible for resolving the access to the shared media. ⦁ In the case of a dedicated link (PPP network), there is no need for the lower layer. ⦁ When nodes or stations are connected and use a common link, called a broadcast link, we need a multiple access protocol to coordinate access to the link. Let us take the more realistic case. ⦁ When a number of stations (users) use a common link of communication system we have to use a multiple access protocol in order to coordinate the access to the common link. [A] Random Access in Media Access Control (MAC): ⦁ In the random access technique, there is no control station. ⦁ Each station will have the right to use the common medium without any control over it. ⦁ With increase in number of stations , there is an increased probability of collision or access conflict. The collisions will occur when more than one user tries to access the common medium simultaneously. (i) Pure Aloha in random access (meaning ‘hello’ in Hawaii): ⦁ Its main principle is to allow any station to broadcast at any time. ⦁ If two signals collide, each station simply waits a random time and try again. ⦁ Collisions are easily detected, when the central station receives a frame it sends an acknowledgment on a different frequency . ⦁ If a user station receives an acknowledgment it assumes that the transmitted frame was successfully received and if it does get an acknowledgment it assumes that collision had occurred and is ready to retransmit. ⦁ It is obvious that we need to resend the frames that have been destroyed during transmission. The pure ALOHA protocol relies mainly on acknowledgments from the receiver. ⦁ Pure ALOHA dictates that when the time-out period passes, each station waits a random amount of time before resending its frame. The randomness will help avoid more collisions. We call this time the back-off time i.e Tb . ⦁ The time-out period is equal to the maximum possible round-trip propagation delay, which is twice the amount of time required to send a frame between the two most widely separated stations. Algorithm Used : ⦁ Transmit one frame and wait for the acknowledgment. ⦁ If acknowledgment received (i.e no collision) then go to step 1. ⦁ If acknowledgment not received(i.e collision has occurred) , select a random time (back off time) for frame retransmission. (ii) Slotted Aloha in Random Access: ⦁ Slotted Aloha is basically introduced to improve the efficiency of pure aloha. As we have already seen that the pure aloha has a vulnerable time of 2 x Tf . ⦁ This is because there is basically no rule that defines when the station can send. ⦁ In slotted ALOHA we divide the time into slots of ‘Tf’ sec and force the station to send only at the beginning of the time slot. If we consider frame transmission time as ‘T’ . ⦁ Collisions occur if any part of two transmission overlaps. Suppose that ‘T’ is time required for one transmission and that two stations must transmit. ⦁ The total time required for both stations to do so successfully is 2T. In case of pure ALOHA allowing a station to transmit at arbitrary times can waste time upto 2T. ⦁ As an alternative, in the slotted ALOHA method the time is divided into intervals (slots) of ‘ T ‘ units each and require each station to begin each transmission at the beginning of a slot. ⦁ In other words, even if the station is ready to send in the middle of a slot, it must wait until the beginning of the next one. In this method a collision occurs when both stations become ready in the same slot. ⦁ The vulnerable period has been reduced to half that of pure ALOHA. ⦁ The slotted ALOHA has a double throughput efficiency than the pure ALOHA system. With increase in the length of the frame or reduction in the propagation time the utilization gets improved. [B] Carrier Sense Multiple Access (CSMA) in Medium Sharing Technique: ⦁ The CSMA protocol operates on the principle of carrier sensing. ⦁ In this protocol. A station first listens to see the presence of transmission (carrier) on the cable and decides to respond accordingly. ⦁ The chance of collision can be reduced if any station senses the medium before trying to use it. ⦁ Carrier sense multiple access (CSMA) requires that each station first listens to the medium (or check the state of the medium) before sending. ⦁ In this way the chances of collision can be reduced by sensing the medium before sending any frames in it. ⦁ The possibility of the collision still exists because of the propagation delay. ⦁ When a station sends a frame, it still takes time (although very short) for the first bit to reach every station (and for each station to sense it). Let us now explore the three types of CSMA: Non-Persistent CSMA: ⦁ In this scheme, if a station wants to transmit a frame and it finds that the channel is busy (some other station is transmitting) then it will wait for a fixed interval of time. ⦁ After this time, it again checks the status of the channel and if the channel is free it will transmit. Persistent CSMA: ⦁ In this scheme the station which wants to transmit, continuously monitors the channel until it is idle and then transmits immediately. ⦁ The disadvantage of this strategy is that if two stations are waiting then they will transmit simultaneously and collision will take place. ⦁ This will then require retransmission. P-Persistent CSMA: ⦁ The possibility of such collisions and retransmissions is reduced in the p-persistent CSMA. ⦁ In this scheme, all the waiting stations are not allowed to transmit simultaneously as soon as the channel becomes idle. A station is assumed to be transmitting with a probability “p”. ⦁ For example if p = 1/5 and if 5 stations are waiting then on an average only one station will transmit and others will wait. [C] Carrier Sense Multiple Access/Collision Detection (CSMA/CD): ⦁ The problem in CSMA explained earlier is that a transmitting station continues to transmit its frame even though a collision occurs. ⦁ The channel time is wasted due to this. In CSMA/CD, if a station receives other transmissions when it is transmitting, then a particular collision can be detected. ⦁ The CSMA method doesn’t specify the procedure following a collision. Carrier sense multiple access with collision detection (CSMA/CD) enhance the algorithm to handle the collision. ⦁ In this method, a station first monitors the medium after it sends a frame to see if the transmission was successful. If so, the station is finished. If there is any collision, the frame is sent again. As soon as a collision is detected, the transmitting stations release a jam signal. The jam signal will alert the other stations. The stations then are not supposed to transmit immediately after the collision has occurred. ⦁ After some “back off” delay time the stations will again retry the transmission. If again the collision takes place then the backoff time is increased further. ⦁ For CSMA/CD to work, we need a specific restriction on the frame size. Before sending the last bit of any frame, the sending station must detect a collision, if any and then it abort the transmission. [D] Carrier Sense Multiple Access/Collision Avoidance (CSMA/CA): ⦁ We need to avoid collisions in the case of wireless networks because they cannot be detected. ⦁ Carrier sense multiple access with collision avoidance (CSMA/CA) was introduced for this network. ⦁ Collisions are avoided through the use of CSMA/CA’s three strategies i.e. the interframe space, the contention window, and the acknowledgments. ⦁ When there is a collision, the station receives two signals i.e. its own signal and the signal is transmitted by a second station. ⦁ To distinguish between these two cases, the received signals in these two cases have to be significantly different. [B] Method Control Access (MCA): Media access control methods act like traffic lights by permitting the smooth flow of traffic on a network, and they prevent or deal with collisions. Media access control methods are implemented at the data-link layer of the Open Systems Interconnection (OSI) reference model. (i) Pooling: ⦁ Polling process is similar to the roll-call performed in class. Just like the teacher, a controller sends a message to each node in turn. ⦁ In this, one acts as a primary station(controller) and the others are secondary stations. All data exchanges must be made through the controller. ⦁ The message sent by the controller contains the address of the node being selected for granting access. ⦁ Although all nodes receive the message but the addressed one responds to it and sends data, if any. If there is no data, usually a “poll reject”(NAK) message is sent back. ⦁ Problems include high overhead of the polling messages and high dependence on the reliability of the controller. Efficiency: Let Tpoll be the time for polling and Tt be the time required for transmission of data. Then, Efficiency = Tt/(Tt + Tpoll) (ii) Token Processing: ⦁ In token passing scheme, the stations are connected logically to each other in form of ring and access of stations is governed by tokens. ⦁ A token is a special bit pattern or a small message, which circulate from one station to the next in the some predefined order. ⦁ In Token ring, token is passed from one station to another adjacent station in the ring whereas incase of Token bus, each station uses the bus to send the token to the next station in some predefined order. ⦁ In both cases, token represents permission to send. If a station has a frame queued for transmission when it receives the token, it can send that frame before it passes the token to the next station. If it has no queued frame, it passes the token simply. ⦁ After sending a frame, each station must wait for all N stations (including itself) to send the token to their neighbors and the other N – 1 stations to send a frame, if they have one. ⦁ There exists problems like duplication of token or token is lost or insertion of new station, removal of a station, which need be tackled for correct and reliable operation of this scheme. Performance Performance of token ring can be concluded by 2 parameters :Delay, which is a measure of time between when a packet is ready and when it is delivered. So, the average time (delay) required to send a token to the next station = a/N. Throughput, which is a measure of the successful traffic. Throughput, S = 1/(1 + a/N) for a<1 and S = 1/{a(1 + 1/N)} for a>1. where N = number of stations a = Tp/Tt (Tp = propagation delay and Tt = transmission delay) [C] Centralization Protocols(CP): (i) FDMA: 1. FDMA stands for Frequency Division Multiple Access. 2. Overall bandwidth is shared among number of stations. 3. Guard bands between adjacent channels is necessary. 4. Synchronization is not required. 5. Power efficiency is less. 6. It requires stability of high carrier efficiency. 7. It is basically used in GSM and PDC. (ii) TDMA: 1. TDMA stands for Time Division Multiple Access. 2. Time sharing of satellite transponder takes place. 3. Guard time between adjacent slots is necessary. 4. Synchronization is necessary. 5. Power efficiency is high. 6. It does not require stability of high carrier efficiency. 7. It is basically used in advanced mobile phone systems. PRACTICAL-5 Aim: Performance comparison of routing protocols. Theory: “Routing Protocols” are the set of defined rules used by the routers to communicate between source & destination. They do not move the information to the source to a destination, but only update the routing table that contains the information. ⦁ “Network Router protocols” helps you to specify way routers communicate with each other. ⦁ It allows the network to select routes between any two nodes on a computer network. Types of Routing Protocols: There are mainly two types of Network Routing Protocols: [A] Static Routing Protocols: ⦁ Static routing protocols are used when an administrator manually assigns the path from source to the destination network. ⦁ It offers more security to the network. Advantages: ⦁ No overhead on router CPU. ⦁ No unused bandwidth between links. ⦁ Only the administrator is able to add routes Disadvantages: ⦁ The administrator must know how each router is connected. ⦁ Not an ideal option for large networks as it is time intensive. ⦁ Whenever link fails all the network goes down which is not feasible in small networks. [B] Dynamic Routing Protocols: ⦁ Dynamic routing protocols are another important type of routing protocol. It helps routers to add information to their routing tables from connected routers automatically. ⦁ These types of protocols also send out topology updates whenever the network changes' topological structure. Advantages: ⦁ Easier to configure even on larger networks. ⦁ It will be dynamically able to choose a different route in case if a link goes down. ⦁ It helps you to do load balancing between multiple links. Disadvantages: ⦁ Updates are shared between routers, so it consumes bandwidth. ⦁ Routing protocols put an additional load on router CPU or RAM. 1) Interior Gateway Protocol (IGP): ⦁ This type of routing protocol is the best for larger network size as it broadcasts after every 90 seconds, and it has a maximum hop count of 255. ⦁ It helps you to sustain larger networks compared to RIP. i) Distance Vector Routing Protocol (DVR): ⦁ “Distance Vector Protocols” advertise their routing table to every directly connected neighbor at specific time intervals using lots of bandwidths and slow converge. ⦁ In the Distance Vector routing protocol, when a route becomes unavailable, all routing tables need to be updated with new information. Advantages: ⦁ Updates of the network are exchanged periodically, and it is always broadcast. ⦁ This protocol always trusts route on routing information received from neighbor routers. Disadvantages: ⦁ As the routing information are exchanged periodically, unnecessary traffic is generated, which consumes available bandwidth. a) Routing Information Protocol (RIP): ⦁ RIP is used in both LAN and WAN Networks. ⦁ It also runs on the Application layer of the OSI model. ⦁ The full form of RIP is the Routing Information Protocol. Two versions of RIP are: *RIPv1: ⦁ The original version or RIPv1 helps you determine network paths based on the IP destination and the hop count journey. ⦁ RIPv1 also interacts with the network by broadcasting its IP table to all routers connected with the network. *RIPv2: ⦁ RIPv2 is a little more sophisticated as it sends its routing table on to a multicast address. b) Interior Gateway Routing Protocol (IGRP): ⦁ IGRP is a subtype of the distance-vector interior gateway protocol developed by CISCO. ⦁ It is introduced to overcome RIP limitations. ⦁ The metrics used are load, bandwidth, delay, MTU, and reliability. It is widely used by routers to exchange routing data within an autonomous system. ii) Link State Routing Protocol: ⦁ Link State Protocols take a unique approach to search the best routing path. ⦁ In this protocol, the route is calculated based on the speed of the path to the destination and the cost of resources. a) Open Shortest Path First (OSPF): ⦁ Open Shortest Path First (OSPF) protocol is a link-state IGP tailor-made for IP networks using the Shortest Path First (SPF) method. ⦁ OSPF routing allows you to maintain databases detailing information about the surrounding topology of the network. ⦁ It also uses the Dijkstra algorithm (Shortest path algorithm) to recalculate network paths when its topology changes. ⦁ This protocol is also very secure, as it can authenticate protocol changes to keep data secure. b)Intermediate System-to-Intermediate System (IS-IS): ⦁ ISIS CISCO routing protocol is used on the Internet to send IP routing information. ⦁ It consists of a range of components, including end systems, intermediate systems, areas, and domains. ⦁ The full form of ISIS is Intermediate System-toIntermediate System. ⦁ Under the IS-IS protocol, routers are organized into groups called areas. Multiple areas are grouped to make form a domain. [C] Hybrid: a)Enhanced Interior Gateway Routing Protocol (EIGRP): ⦁ EIGRP is a hybrid routing protocol that provides routing protocols, distance vector, and link-state routing protocols. ⦁ The full form routing protocol EIGRP is Enhanced Interior Gateway Routing Protocol. ⦁ It will route the same protocols that IGRP routes using the same composite metrics as IGRP, which helps the network select the best path destination. 2) Exterior Gateway Protocol (EGP): ⦁ EGP is a protocol used to exchange data between gateway hosts that are neighbors with each other within autonomous systems. ⦁ This routing protocol offers a forum for routers to share information across different domains. ⦁ The full form for EGP is the Exterior Gateway Protocol. EGP protocol includes known routers, network addresses, route costs, or neighboring devices. a) Border Gateway Protocol (BGP): ⦁ BGP is the last routing protocol of the Internet, which is classified as a DPVP (distance path vector protocol). ⦁ The full form of BGP is the “Border Gateway Protocol”. ⦁ This type of routing protocol sends updated router table data when changes are made. Therefore, there is no autodiscovery of topology changes, which means that the user needs to configure BGP manually. PRACTICAL-6(a) Aim: Write a program to implement echo server and client in java using TCP sockets. Source Code: EchoClient.java: import java.io.*; import java.net.*; public class EchoClient{ public static void main(String[] args){ try { Socket s = new Socket("127.0.0.1", 9999); BufferedReader r = new BufferedReader(new InputStreamReader(s.getInputStream())); PrintWriter w = new PrintWriter(s.getOutputStream(), true); BufferedReader con = new BufferedReader(new InputStreamReader(System.in)); String line; do{ line = r.readLine(); if ( line != null ) System.out.println(line); line = con.readLine(); w.println(line); } while ( !line.trim().equals("bye") ); } catch (Exception err){ System.err.println(err); } } } EchoServer.java: import java.io.*; import java.net.*; public class EchoServer { public EchoServer(intportnum) { try{ server = new ServerSocket(portnum); } catch (Exception err){ System.out.println(err); } } public void serve(){ try{ while (true){ Socket client = server.accept(); BufferedReader r = new BufferedReader(new InputStreamReader(client.getInputStream())); PrintWriter w = new PrintWriter(client.getOutputStream(),true); w.println("Welcome to the Java EchoServer. Type 'bye' to close."); String line; do{ line = r.readLine(); if ( line != null ) w.println("Got: "+ line); System.out.println (line); } while ( !line.trim().equals("bye") ); client.close(); } } catch (Exception err){ System.err.println(err); } } public static void main(String[] args){ EchoServer s = new EchoServer(9999); s.serve(); } private ServerSocket server; } Output: EchoClient.java: EchoServer.java: PRACTICAL-6(b) Aim: Write a program to implement date server and client in java using TCP sockets. Source Code: DateClient.java: import java.io.*;import java.net.*;class DateClient{ publicstaticvoid main(String args[]) throws Exception { Socket soc=new Socket(InetAddress.getLocalHost(),5217); BufferedReader in=new BufferedReader( new InputStreamReader( soc.getInputStream() ) ); System.out.println(in.readLine()); } } DateServer.java: import java.net.*;import java.io.*;import java.util.*;class DateServer{ publicstaticvoid main(String args[]) throws Exception { ServerSocket s=new ServerSocket(5217); while(true) { System.out.println("Waiting For Connection ..."); Socket soc=s.accept(); DataOutputStream out=new DataOutputStream(soc.getOutputStream()); out.writeBytes("Server Date" + (new Date()).toString() + "\n"); out.close(); soc.close(); } }} Output: DateClient.java: DateServer.java: PRACTICAL-6(c) Aim: Write a program to implement a chat server and client in java using TCP sockets. Source Code: ChatClient.java: import java.net.*; import java.io.*; public class ChatClient { private String hostname; private int port; private String userName; public ChatClient(String hostname, int port) { this.hostname = hostname; this.port = port; } public void execute() { try { Socket socket = new Socket(hostname, port); System.out.println("Connected to the chat server"); new ReadThread(socket, this).start(); new WriteThread(socket, this).start(); } catch (UnknownHostException ex) { System.out.println("Server not found: " + ex.getMessage()); } catch (IOException ex) { System.out.println("I/O Error: " + ex.getMessage()); } } void setUserName(String userName) { this.userName = userName; } String getUserName() { return this.userName; } public static void main(String[] args) { if (args.length< 2) return; String hostname = args[0]; int port = Integer.parseInt(args[1]); ChatClient client = new ChatClient(hostname, port); client.execute(); } } ChatServer.java: import java.io.*; import java.net.*; import java.util.*; public class ChatServer { private int port; private Set<String>userNames = new HashSet<>(); private Set<UserThread>userThreads = new HashSet<>(); public ChatServer(int port) { this.port = port; } public void execute() { try (ServerSocketserverSocket = new ServerSocket(port)) { System.out.println("Chat Server is listening on port " + port); while (true) { Socket socket = serverSocket.accept(); System.out.println("New user connected"); UserThreadnewUser = new UserThread(socket, this); userThreads.add(newUser); newUser.start(); } } catch (IOException ex) { System.out.println("Error in the server: " + ex.getMessage()); ex.printStackTrace(); } } public static void main(String[] args) { if (args.length< 1) { System.out.println("Syntax: java ChatServer<port-number>"); System.exit(0); } int port = Integer.parseInt(args[0]); ChatServer server = new ChatServer(port); server.execute(); } void broadcast(String message, UserThreadexcludeUser) { for (UserThreadaUser : userThreads) { if (aUser != excludeUser) { aUser.sendMessage(message); } } } void addUserName(String userName) { userNames.add(userName); } void removeUser(String userName, UserThreadaUser) { boolean removed = userNames.remove(userName); if (removed) { userThreads.remove(aUser); System.out.println("The user " + userName + " quitted"); } } Set<String>getUserNames() { return this.userNames; } booleanhasUsers() { return !this.userNames.isEmpty(); } } ReadThread.java: import java.io.*; import java.net.*; public class ReadThread extends Thread { private BufferedReader reader; private Socket socket; private ChatClient client; public ReadThread(Socket socket, ChatClient client) { this.socket = socket; this.client = client; } try { InputStream input = socket.getInputStream(); reader = new BufferedReader(new InputStreamReader(input)); } catch (IOException ex) { System.out.println("Error getting input stream: " + ex.getMessage()); ex.printStackTrace(); } } public void run() { while (true) { try { String response = reader.readLine(); System.out.println("\n" + response); if (client.getUserName() != null) { System.out.print("[" + client.getUserName() + "]: "); } } catch (IOException ex) { System.out.println("Error reading from server: " + ex.getMessage()); ex.printStackTrace(); break; } } } } UserThread.java: import java.io.*; import java.net.*; import java.util.*; public class UserThread extends Thread { private Socket socket; private ChatServer server; private PrintWriter writer; public UserThread(Socket socket, ChatServer server) { this.socket = socket; this.server = server; } public void run() { try { InputStream input = socket.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(input)); OutputStream output = socket.getOutputStream(); writer = new PrintWriter(output, true); printUsers(); String userName = reader.readLine(); server.addUserName(userName); String serverMessage = "New user connected: " + userName; server.broadcast(serverMessage, this); String clientMessage; do { clientMessage = reader.readLine(); serverMessage = "[" + userName + "]: " + clientMessage; server.broadcast(serverMessage, this); } while (!clientMessage.equals("bye")); server.removeUser(userName, this); socket.close(); serverMessage = userName + " has quitted."; server.broadcast(serverMessage, this); } catch (IOException ex) { System.out.println("Error in UserThread: " + ex.getMessage()); ex.printStackTrace(); } } void printUsers() { if (server.hasUsers()) { writer.println("Connected users: " + server.getUserNames()); } else { writer.println("No other users connected"); } } void sendMessage(String message) { writer.println(message); } } WriteThread.java: import java.io.*; import java.net.*; public class WriteThread extends Thread { private PrintWriter writer; private Socket socket; private ChatClient client; public WriteThread(Socket socket, ChatClient client) { this.socket = socket; this.client = client; try { OutputStream output = socket.getOutputStream(); writer = new PrintWriter(output, true); } catch (IOException ex) { System.out.println("Error getting output stream: " + ex.getMessage()); ex.printStackTrace(); } } public void run() { Console console = System.console(); String userName = console.readLine("\nEnter your name: "); client.setUserName(userName); writer.println(userName); String text; do { text = console.readLine("[" + userName + "]: "); writer.println(text); } while (!text.equals("bye")); try { socket.close(); } catch (IOException ex) { System.out.println("Error writing to server: " + ex.getMessage()); } } } Output: ChatClient.java: ChatServer.java: PRACTICAL-7(a) Aim: Write a program to implement echo server and client in java using UDP sockets. Source Code: Client.java: import java.io.*; import java.net.*; public class Client { public static void main(String args[]) throws Exception { intclientport = 7777; String host = "localhost"; if (args.length< 1) { System.out.println("Usage: UDPClient " + "Now using host = " + host + ", Port# = " + clientport); } else { clientport = Integer.valueOf(args[0]).intValue(); System.out.println("Usage: UDPClient " + "Now using host = " + host + ", Port# = " + clientport); } InetAddressia = InetAddress.getByName(host); SenderThread sender = new SenderThread(ia, clientport); sender.start(); } } class SenderThread extends Thread { private InetAddressserverIPAddress; private DatagramSocketudpClientSocket; private boolean stopped = false; private intserverport; public SenderThread(InetAddress address, intserverport) throws SocketException { this.serverIPAddress = address; this.serverport = serverport; this.udpClientSocket = new DatagramSocket(); this.udpClientSocket.connect(serverIPAddress, serverport); } public void halt() { this.stopped = true; } public DatagramSocketgetSocket() { return this.udpClientSocket; } public void run() { try { BufferedReaderinFromUser = new BufferedReader(new InputStreamReader(System.in)); while (true) { if (stopped) return; String clientMessage = inFromUser.readLine(); if (clientMessage.equals(".")) break; byte[] sendData = new byte[100]; sendData = clientMessage.getBytes(); DatagramPacketsendPacket = new DatagramPacket(sendData, sendData.length, serverIPAddress, serverport); udpClientSocket.send(sendPacket); Thread.yield(); } } catch (IOException ex) { System.err.println(ex); } } } Server.java: import java.net.*; import java.util.HashSet; public class Server { private static HashSet<Integer>portSet = new HashSet<Integer>(); public static void main(String args[]) throws Exception { intserverport = 7777; if (args.length< 1) { System.out.println("Usage: UDPServer " + "Now using Port# = " + serverport); } else { serverport = Integer.valueOf(args[0]).intValue(); System.out.println("Usage: UDPServer " + "Now using Port# = " + serverport); } DatagramSocketudpServerSocket = new DatagramSocket(serverport); System.out.println("Server started...\n"); while(true) { byte[] receiveData = new byte[100]; DatagramPacketreceivePacket = new DatagramPacket(receiveData, receiveData.length); udpServerSocket.receive(receivePacket); String clientMessage = (new String(receivePacket.getData())).trim(); System.out.println("Client Connected - Socket Address: " + receivePacket.getSocketAddress()); System.out.println("Client message: \"" + clientMessage + "\""); InetAddressclientIP = receivePacket.getAddress(); System.out.println("Client IP Address & Hostname: " + clientIP + ", " + clientIP.getHostName() + "\n"); intclientport = receivePacket.getPort(); String returnMessage = clientMessage.toUpperCase(); byte[] sendData = new byte[1024]; sendData = returnMessage.getBytes(); for(Integer port : portSet) { if(port != clientport) { DatagramPacketsendPacket = new DatagramPacket(sendData, sendData.length, clientIP, clientport); udpServerSocket.send(sendPacket); } } } } } Output: Client.java: Server.java: PRACTICAL-7(b) Aim: Write a program to implement DNS server and client in java using UDP sockets. Source Code: Client.java: import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; public class Client { public static void main(String[] args) throws SocketException, IOException { BufferedReaderclientRead =new BufferedReader(new InputStreamReader(System.in)); InetAddress IP = InetAddress.getByName("127.0.0.1"); DatagramSocketclientSocket = new DatagramSocket(); while(true) { byte[] sendbuffer = new byte[70]; byte[] receivebuffer = new byte[70]; System.out.print("\nClient: "); String clientData = clientRead.readLine(); sendbuffer = clientData.getBytes(); DatagramPacketsendPacket =new DatagramPacket(sendbuffer, sendbuffer.length, IP, 9876); clientSocket.send(sendPacket); if(clientData.equalsIgnoreCase("bye")) { System.out.println("Connection ended by client"); break; } DatagramPacketreceivePacket =new DatagramPacket(receivebuffer, receivebuffer.length); clientSocket.receive(receivePacket); String serverData = new String(receivePacket.getData()); System.out.print("\nServer: " + serverData); } clientSocket.close(); } } Server.java: import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; public class Server { public static void main(String[] args) throws SocketException, IOException { DatagramSocketserverSocket = new DatagramSocket(9876); while(true) { byte[] receivebuffer = new byte[70]; byte[] sendbuffer = new byte[70]; DatagramPacketrecvdpkt = new DatagramPacket(receivebuffer, receivebuffer.length); serverSocket.receive(recvdpkt); InetAddress IP = recvdpkt.getAddress(); intportno = recvdpkt.getPort(); String clientdata = new String(recvdpkt.getData()); System.out.println("\nClient : "+ clientdata); System.out.print("Server : "); BufferedReaderserverRead = new BufferedReader(new InputStreamReader (System.in) ); String serverdata = serverRead.readLine(); sendbuffer = serverdata.getBytes(); DatagramPacketsendPacket = new DatagramPacket(sendbuffer, sendbuffer.length, IP,portno); serverSocket.send(sendPacket); //here the check condition for serverdata which must be bye if(serverdata.equalsIgnoreCase("bye")) { System.out.println("connection ended by server"); break; } } serverSocket.close(); } } Output: Client.java: Server.java: PRACTICAL-7(c) Aim: Write a program to implement echo server and client in java using UDP sockets. Source Code: UDPClient.java: import java.io.*; import java.net.*; public class UDPClient{ public static void main(String args[])throws IOException{ BufferedReaderbr = new BufferedReader(new InputStreamReader(System.in)); DatagramSocketclientsocket = new DatagramSocket(); InetAddressipaddress; if (args.length == 0) ipaddress = InetAddress.getLocalHost(); else ipaddress = InetAddress.getByName(args[0]); byte[] senddata = new byte[70]; byte[] receivedata = new byte[70]; intportaddr = 1362; System.out.print("Enter the Hostname : "); String sentence = br.readLine(); senddata = sentence.getBytes(); DatagramPacket pack = new DatagramPacket(senddata,senddata.length,ipaddress,portaddr); clientsocket.send(pack); DatagramPacketrecvpack =new DatagramPacket(receivedata,receivedata.length); clientsocket.receive(recvpack); String modified = new String(recvpack.getData()); System.out.println("IP Address: " + modified); clientsocket.close(); } } UDPServer.java: import java.io.*; import java.net.*; public class UDPServer { private static intindexOf(String[] array, String str){ str = str.trim(); for (inti=0; i<array.length; i++){ if (array[i].equals(str)) return i; } return -1; } public static void main(String arg[])throws IOException{ String[] hosts = {"zoho.com", "gmail.com","google.com", "facebook.com"}; String[] ip = {"172.28.251.59", "172.217.11.5","172.217.11.14", "31.13.71.36"}; System.out.println("Press Ctrl + C to Quit"); while (true) { DatagramSocketserversocket=new DatagramSocket(1362); byte[] senddata = new byte[70]; byte[] receivedata = new byte[70]; DatagramPacketrecvpack = new DatagramPacket(receivedata,receivedata.length); serversocket.receive(recvpack); String sen = new String(recvpack.getData()); InetAddressipaddress = recvpack.getAddress(); int port = recvpack.getPort(); String capsent; System.out.println("Request for host nameis = " + sen); if(indexOf (hosts, sen) != -1) capsent = ip[indexOf (hosts, sen)]; else capsent = "Host Not Found"; senddata = capsent.getBytes(); DatagramPacket pack = new DatagramPacket (senddata,senddata.length,ipaddress,port); serversocket.send(pack); serversocket.close(); } } } Output: UDPClient.java: UDPServer.java: PRACTICAL-8 Aim: To implement simple calculator and invoke arithmetic operations from a remote client. Source Code: MyClient.java: import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; import java.util.Scanner; public class MyClient { public static void main(String[] args) throws IOException { InetAddressip = InetAddress.getLocalHost(); int port = 4444; Scanner sc = new Scanner(System.in); Socket s = new Socket(ip, port); DataInputStream dis = new DataInputStream(s.getInputStream()); DataOutputStream dos = new DataOutputStream(s.getOutputStream()); while (true) { System.out.print("Enter the expression in the form: "); System.out.println("'operand operator operand'"); String inp = sc.nextLine(); if (inp.equals("bye")) break; dos.writeUTF(inp); String ans = dis.readUTF(); System.out.println("Answer=" + ans); } } } MyServer.java: import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.StringTokenizer; public class MyServer { public static void main(String args[]) throws IOException { ServerSocketss = new ServerSocket(4444); Socket s = ss.accept(); DataInputStream dis = new DataInputStream(s.getInputStream()); DataOutputStream dos = new DataOutputStream(s.getOutputStream()); while (true) { String input = dis.readUTF(); if(input.equals("bye")) break; System.out.println("Equation received: " + input); int result; StringTokenizerst = new StringTokenizer(input); int oprnd1 = Integer.parseInt(st.nextToken()); String operation = st.nextToken(); int oprnd2 = Integer.parseInt(st.nextToken()); if (operation.equals("+")) { result = oprnd1 + oprnd2; } else if (operation.equals("-")) { result = oprnd1 - oprnd2; } else if (operation.equals("*")) { result = oprnd1 * oprnd2; } else { result = oprnd1 / oprnd2; } System.out.println("Sending the result..."); dos.writeUTF(Integer.toString(result)); } } } Output: MyClient.java: MyServer.java: PRACTICAL-9 Aim: To implement bubble sort and sort data using a remote client. Source Code: MyClient.java: import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; import java.util.Scanner; import java.lang.*; import java.util.*; public class MyClient { public static void main(String[] args) throws IOException { InetAddressip = InetAddress.getLocalHost(); int port = 4444; Scanner sc = new Scanner(System.in); Socket s = new Socket(ip, port); DataInputStream dis = new DataInputStream(s.getInputStream()); DataOutputStream dos = new DataOutputStream(s.getOutputStream()); while (true) { System.out.print("Enter the Array of Size 5(To Quit enter bye):\n "); String inp = sc.nextLine(); if (inp.equals("bye")) break; dos.writeUTF(inp); String ans = dis.readUTF(); System.out.println("Answer=" + ans); ans = dis.readUTF(); System.out.println(ans); } } } MyServer.java: import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.StringTokenizer; import java.lang.*; import java.util.*; public class MyServer { public static void main(String args[]) throws IOException { int a[]={0,0,0,0,0}; ServerSocketss = new ServerSocket(4444); Socket s = ss.accept(); DataInputStream dis = new DataInputStream(s.getInputStream()); DataOutputStream dos = new DataOutputStream(s.getOutputStream()); while (true) { String input = dis.readUTF(); if(input.equals("bye")) break; System.out.println("Equation received: " + input); int result; StringTokenizerst = new StringTokenizer(input); int oprnd1 = Integer.parseInt(st.nextToken()); int oprnd2 = Integer.parseInt(st.nextToken()); int oprnd3 = Integer.parseInt(st.nextToken()); int oprnd4 = Integer.parseInt(st.nextToken()); int oprnd5 = Integer.parseInt(st.nextToken()); a[0]=oprnd1; a[1]=oprnd2; a[2]=oprnd3; a[3]=oprnd4; a[4]=oprnd5; System.out.println("Sending the result..."); bubbleSort(a,5); printArray(a,5); dos.writeUTF("Array Sort Successfull..!!"); dos.writeUTF(Arrays.toString(a)); } } static void bubbleSort(intarr[], int n) { inti, j, temp; boolean swapped; for (i = 0; i< n - 1; i++) { swapped = false; for (j = 0; j < n - i - 1; j++) { if (arr[j] >arr[j + 1]) { // swap arr[j] and arr[j+1] temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; swapped = true; } } if (swapped == false) break; } } static void printArray(intarr[], int size) { inti; for (i = 0; i< size; i++) System.out.print(arr[i] + " "); System.out.println(); } } Output: MyClient.java: MyServer.java: PRACTICAL-10 Aim: To simulate a sliding window protocol that uses Go Back N ARQ. Source Code: MyClient.java: import java.lang.System; import java.net.*; import java.io.*; public class MyClient { static Socket connection; public static void main(String a[]) throws SocketException { try { int v[] = new int[9]; int n = 0; InetAddressaddr = InetAddress.getByName("Localhost"); System.out.println(addr); connection = new Socket(addr, 8011); DataOutputStream out = new DataOutputStream( connection.getOutputStream()); DataInputStream in = new DataInputStream( connection.getInputStream()); int p = in.read(); System.out.println("No of frame is:" + p); for (inti = 0; i< p; i++) { v[i] = in.read(); System.out.println(v[i]); } v[5] = -1; for (inti = 0; i< p; i++) { System.out.println("Received frame is: " + v[i]); } for (inti = 0; i< p; i++) if (v[i] == -1) { System.out.println("Request to retransmit packet no " + (i+1) + " again!!"); n = i; out.write(n); out.flush(); } System.out.println(); v[n] = in.read(); System.out.println("Received frame is: " + v[n]); System.out.println("quiting"); } catch (Exception e) { System.out.println(e); } } } MyServer.java: import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; public class MyServer { static ServerSocketServersocket; static DataInputStream dis; static DataOutputStream dos; public static void main(String[] args) throws SocketException { try { int a[] = { 30, 40, 50, 60, 70, 80, 90, 100, 110 }; Serversocket = new ServerSocket(8011); System.out.println("waiting for connection"); Socket client = Serversocket.accept(); dis = new DataInputStream(client.getInputStream()); dos = new DataOutputStream(client.getOutputStream()); System.out.println("The number of packets sent is:" + a.length); int y = a.length; dos.write(y); dos.flush(); for (inti = 0; i<a.length; i++) { dos.write(a[i]); dos.flush(); } int k = dis.read(); dos.write(a[k]); dos.flush(); } catch (IOException e) { System.out.println(e); } finally { try { dis.close(); dos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } Output: MyClient.java: MyServer.java: