Network Programming in Java

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 56

NETWORK PROGRAMMING IN JAVA

INTRODUCTION In the 1980s, the US governments Advanced Research Projects Agency (ARPA) provided funds to the University of California at Berkeley to implement TCP/IP protocols under the UNIX operating system. During this project, a group of Berkeley researchers developed an application program interface (API) for TCP/IP network communications called the socket interface. for TCP/IP networks. The socket interface designers originally built their interface into the UNIX operating system. However, the other operating systems, environments, such as Microsoft Windows, implement the socket interface as software libraries. However, regardless of the environment in which we program, the program code will look much the same. NETWORK PROGRAMMING The core of a network application consists of a pair of programs, a client program and server program. When these two programs are executed, a client and a server process are created, and these two processes communicate with each other by reading from and writing to sockets. A socket is a software abstraction for an input or output medium of communication. It is a communication channel that enables you to transfer data through a certain port. A port is a software abstraction that provides a means to differentiate between network services. More specifically, a port is a 16-bit number identifying the different services offered by a network server. Each computer on the Internet has a bunch of ports that can be assigned different services. To use a particular service and therefore establish a line of communication via a particular protocol, we must connect to the correct port. Ports are numbered, and some of the numbers are specifically associated with a type of service. Ports with specific service assignments are known as standards ports. For example, 1 The socket interface is an API TCP/IP networks i.e. it defines a variety of software functions or routines for the development of applications

the FTP service is located on port 21, so any computer wanting to perform an FTP file transfer would connect to port 21 of the host computer. Likewise, the HTTP service is located on port 80, so any time we access a Web site, we are really connecting to port 80 of the host using the HTTP protocol behind the scenes. All standard service assignments are given port values below 1024. This means that ports above 1024 are considered for custom communications, such as those required by a java client/server program implementing its own protocol. TCP/IP lets the network programs use connection-oriented or connectionless network communication. The TCP/IP protocol suite supports these using two different protocols, TCP (Transport Control Protocol) and UDP (User Datagram Protocol). NETWORK PROGRAMMING WITH TCP TCP is a connection oriented, transport layer protocol that works on top of IP (Internet Protocol). In connection oriented network communication, data flows as a single, serial stream of bytes without record or other type of boundaries. Connection-oriented communications use virtual circuits the link between the endpoints appears to be a point-point connection. The virtual circuit is permanent throughout the session between the local and the remote host. In other words, after the network software establishes the connection, the program can exchange data with the remote host in a steady byte stream. The circuit has to be established before data transfer begins. A connection is based on the host IP address and the port that the server is listening on. Processes running on different machines communicate with each other by sending message into sockets. Each process is analogous to a house and the processs socket is analogous to a door. As shown in the following diagram, the socket is the door between the application process and TCP. The application developer has control of everything on the application-layer side of the socket. The client has to initiate the contact with the server. In order to react to the clients initial contact, the server must be running as a process before the client attempts to initiate contact. Also the server must have some sort of a door i.e. a socket that welcomes the 2

initial contact from a client running on an arbitrary machine. With the server process running, the client process can initiate a TCP connection to the server. This is done in the client program by creating a socket object. When the client creates its socket object, it specifies the address of the server process, namely, the IP address of the server and the port number of the process. Upon creation of the socket object, TCP in the client establishes a TCP connection with the server. From the applications perspective, the TCP connection is a direct virtual pipe between the clients socket and the servers connection socket. The client process can send arbitrary bytes into its socket. TCP guarantees that the server process will receive through the connection socket, each byte in the order sent. The client process can also receive byte from its socket and the server process can also send bytes into its connection socket. This is illustrated in the following diagram. referred to as socket programming. NETWORK PROGRAMMING WITH UDP UDP is a connectionless transport layer protocol that also sits on top of IP. packets called datagrams. In Because sockets play a central role in client-server applications, client-server application development is also

connectionless network communication, data travels in separate, self-contained data Unlike TCP, UDP provides no data integrity mechanisms except for a single checksum, and unlike TCP, dose not establish a connection to the destination before sending any data. UDP simply packages its data with the destination address and port number and sends it out onto the network. If the destination host is live and listening it will receive the datagram, if not it will be discarded. Because there is no guaranteed delivery, as there is with TCP, there is a possibility that datagrams will be lost, corrupted or delivered in wrong order. Clearly, UDP isnt a good match for applications like FTP that require reliable transmission of data over potentially unreliable networks. However there are many kinds of applications in which raw speed is more important than getting every bit right. We can use sockets for connection-oriented or connectionless communications.

CLIENT SERVER APPLICATIONS There are two sorts of client server applications. One sort is a client-server application that is an implementation of a protocol standard defined in an RFC. For such an implementation, the client and server programs must conform to the rules dictated by the RFC. For example, the client program could be an implementation of the FTP client, defined in RFC 959, and the server program could be an implementation of the FTP server, also defined in RFC 959. If one developer writes code for the client program and an independent developer writes code for the server program, and both developers carefully follow the rules of the RFC, then the two programs will be able to iteroperate. Indeed, most of todays network applications involve communication between client and server programs that have been created by independent developers. For example a FTP client on a PC can upload a file to a Unix FTP server. When a client or server program implements a protocol defined in an RFC it should use the port number associated with the protocol. The other sort of client-server application is a proprietary client-server application. In this case the client and server programs do not necessarily conform to any existing RFC. A single developer or development team creates both the client and server programs, and the developer has complete control over what he puts in the code. But because the code does not implement a public-domain protocol, other independent developers will not be able to develop code that interoperates with the application. When developing a proprietary application, the developer must be careful not to use one of the well-known port numbers defined in the RFCs. During the development phase of a proprietary client-server application, one of the first decisions the developer must make is whether the application is to run over TCP or over UDP. SOME CLARIFICATIONS: IP ADDRESS

Java works with in the Internet, which requires a way to uniquely identify a machine from all the others in the world. This is accomplished with the IP address that can exist in two forms: 1. The DNS form-our domain name is Klnce.edu, so suppose we have a computer called system in our domain. system1.Klnce.edu. 2. In the another form, every computer in the network identified by a unique 32bit number, which is typically written as a group of four numbers separated by dots. E.g. 196.168.1.201 In Java, special class called InetAddress represents the IP address. get an instance of InetAddress class. InetAddress getLocalhost() InetAddress getByName() InetAddress[] getAllByName() SERVERS AND CLIENTS The Java network-programming model is based on Client/Server model. The machine that stays in one place is called the server, and that one seeks for connection is called the Client. This distinction is only important while the client tries to make a connection to the server. Once they have connected is becomes a two-way communication process. PORTS An IP Address is not enough to identify a unique server, because many server programs may exists on one machine. So we need a unique identification for each server. This unique identification is referred to as port. When we are setting up client or a server we must choose a port to where both client and server agree to meet. This port is not a The Its domain name would be

InetAddress class doesnt have a constructor, but provides three static methods to

physical port, but a logical port specified by a 16-bit number. The port numbers 0 to 1024 are already used by common applications like FTP, TELNET etc. SOCKETS The socket is the software abstraction used to represent the terminals of a connection between two machines. For a given connection, there is socket on each machine. In Java, we create socket to make a connection to the other machine, then we get InputStream and OutputputStream from the socket in order to able to keep the connection as an I/O streams objects. At this point, you use methods getInputStream() and getOutputStream() to produce the corresponding InputStream and OutputStream objects from each socket. The server socket class Serversocket in the network in the network package java.net can be used to create a server or listening Socket. This Serversocket listens for incoming connections and then returns an established socket through accept() method. The accept() method of Serversocket waits until some other machine connects to it and returns an actual socket. DATAGRAMS The Transmission Control Protocol (TCP), which is designed for ultimate reliability and

which guarantees that the data will reach safely to the other end. The second protocol called UserDatagram Protocol(UDP), doesnt guarantee that the packets will be delivered in order. It is called an unreliable protocol but, is very faster than the reliable TCP. In Java, UDP client and server objects can be created using DatagramSocket class. But there is no any Serversocket that waits for a connection, because there is no connection held between two ends. The Datagram packet itself must know the Source and Destination address. A Datagramsocket sends and receives packets and the DatagramPacket contains the information itself. When we are receiving a datagram, we only need to provide a buffer where the data will be placed. The constructor for a DatagramPacket to receice datagram is declared as, 6

DatagramPacket (byte[] buf, int buf.length) Where buf is the array of byte. When we send a datagram, the DatagramPacket must contain not only the data, but also the IP address and port it will be sent. DatagramPacket is DatagramPacket (byte[] buf, int length, InetAddress ia, int port) Buf Contains the data that wewant to send out. Length is the length of the buf. ACCESSING WWW RESOURCES Java provides a flexible URL and URL connection class to obtain information from resources on the network that has a URL address. We can create a URL class instance for a WWW address and then use the getContent() method for the URL class to download the content.java supports only the text/plain, image/gif and image/jpeg data types. USING URL AND URL CONNECTION We can create URLs by specifying a single string value for the entire URL address, or separate values for the protocols (IITTP, FTP and so on), host name, port number and file path. We can also create a URL by specifying a string value. Creating an URL class instance can throw the MalformedURLException. So the constructot for the outgoing

SCOKET PROGRAMMING IN JAVA Socket programming can be done in any language, which supports network communication, but java is preferred because it is platform independent, it has exception mechanisms for robust handling of common problems that occur during I/O and networking operations. One of javas major strong suits as a programming language for client-server application development is its wide range of network support. Java has this advantage because it was developed with the Internet in mind. The result is that we have a lot of options in regard to network programming in Java. Java performs all of its

network communication through sockets. Java provides basic socket classes to make programming with sockets much easier. Java sockets are broken down into two types: datagram sockets and stream sockets. DATAGRAM SOCKETS A datagram socket uses UDP to facilitate the sending of datagrams in an unreliable manner. Unreliable means that information sent via datagrams isnt guaranteed to reach the destination. The trade-off here is that datagram sockets require relatively few Datagram are sent as resources because of this unreliable design, the clients and sent servers in a datagram scenario dons require a dedicated network connection. individually bundled packets that may or may not reach the destination in any particular order or at any particular time. For this reason datagrams include a sequence number that specifies the order. The receiver has to wait to receive the entire sequence and put them back in the original order. Java supports datagram socket programming through two classes DatagramSocket and DatagramPacket. The DatagramSocket class provides an implemention for a basic datagram socket. The DatagramPacket class provides the functionally required to send a packet of information through a datagram socket. The methods implemented in the DatagramSocket class are DatagramSocket() DatagramSocket(int port) Void send(DatagramPacket p) Void close() This is the default constructor used to create a socket This is also a constructor which is used to create a Socket which is connected to a specific port. To send a datagram packet p To receive a datagram packet p To close the connection Void receive (DatagramPacket p) -

The methods implemented in the DatagramPacket class are

DatagramPacket (byte buf[], int length) datagrams, but is a the maximum number of bytes to read.

This is a constructor used to receive

byte array that holds the data received and length is

DatagramPacket(byte buf[], int length, InetAddress addr, int port) - This is a constructor to send datagrams to the specified Address. Byte getData() Int getLength() STREAM SOCKETS A stream socket is a connected socket through which data is sent continuously. Because the communication link is dedicated, it is reliable. Java supports stream socket programming through two classes: Socket and ServerScoket. The Socket class provides the necessary overhead to facilitate a stream socket client and the ServerSocket class provides the core functionality for a server. The methods implemented in this Socket class are Socket (String host, int port) specified host host can be be in a range of 1- 65535. Socket (InetAddress addr, int port) This creates a stream socket and connects to the specified host and Port. Inputstream getInputStream() - This returns an InputStream that allows the socket to - This creates a stream socket and connects to the a host name or IP address and port must - To return the data received in the socket. - To return the length of the datagram packet.

receive data across the TCP connection. Outputstream getoutputStream() - This returns an outputStream that allows the socket to send data across the TCP connection.

The methods implemented in the ServerSocket class are ServerSocket (int port) - This is a constructor used to create a server socket.

ServerSocket (int port, int count) - This is a constructor used to create a server socket. The count parameter specifies a timeout period for the server to quit automatically listening for a client connection. Socket accept() - To tell the server to wait for a client connection. This

blocks Program flow until a connection is made. Void close() - To terminate the connection.

WINDOWS SOCKETS PROGRAMMING This part is designed to give the programmer enough information to know where to look to get the actual information. What is Windows Sockets? Windows Sockets, or Winsock, is a .DLL, which allows applications to talk over a network, usually the Internet. The .DLL is usually called WINSOCK.DLL. Where do I get Windows Sockets? Unlike all other .DLLs, theirs isnt an official WINSOCK.DLL in the sense that there is say a common dialogCOMMDLG.DLL or a control 3d CTL3DV2.DLL. When you get WINSOCK, you get it from a particular vendor. Each different version is slightly different in terms of how it is configured, but once it is configured properly each .DLL should have the same functions and properly written applications will work with whatever Winsock you are using.

10

Popular Winsocks are: 1. Trumpet Winsock 2. Wolveerine 3. FTP Softwares Winsock 4. Windows 95 Winsock 5. Windows NT Winsock What do I need to write a C/C++ program that talks to Winsock? You need a .h file which lists the data types and function calls used by Winsock. If you are programming 16 bit Windows 3.1 or WfWG 3.11 apps, you also need WINSOCK.LIB so that you can link. You also want the .HLP file, which contains the documentation. You can get all of these things from Stardust Winsock 1.1 Development Components. Here is what is provided: Winsock documentation on HTML format for reading online. Winsock .HLP file, .H file, and .LIB file. Winsock .WRI file, which is the .HLP file in Windows Write format, for printing. Note that it doesnt matter whose Winsock you are using, the same .LIB file works with all 16-bit programs, and you dont need a .LIB for 32 bit programs. Also note that these versions are a bit more recent than the version in the WINSOCK.HLP normally shipped with C++. If you are using Borland C++ 4.0 you got a free WINSOCK.HLP and WINSOCK.H, but no WINSOCK.DLL, so your programs cant link. You can use the provided IMPLIB to make a WINSOCK.LIB from your WINSOCK.DLL.

11

TCP/IP is the Internet Protocol. Most Winsocks speak TCP/IP. If you are on a NetWare LAN, your LAN might speak IPX/SPX as its native protocol. That doesnt matter, because in most cases TCP/IP and IPX/SPX can live on the same Ethernet in harmony, not even being aware of the others existence. To get this to work with Trumpet you will have to alter your NET.CFG. If you are connecting to the Internet with a modem, you are probably used to the way that a communications terminal program, like Windows Terminal, dials a phone number and than each character sent over the modem reaches the other end, where the other end is some program running on the computer in charge of the modem at the end. Network protocols dont work like this. On the Internet, each machine is given an address, which is four numbers, such as 1.2.3.4. You send data in chunks called packets and you tell TCP/IP the address of the machine that you want to get the data, and the 16-bit socket number of the program running on that machine that you want to get the data. TCP/IP sends your packet and provides a way for the other program to get a response back to you.

12

Network Programming Concepts in C


Here consider the discussion of 1. 2. 3. 4. 1. DATA COMPRESSION All compression systems require two algorithms: One for compressing the data at the source, and another for decompressing it at the destination. In the literature, these algorithms are referred to as the encoding and decoding algorithms, respectively. Encrypt Encoding Compression schemes can be divided into two general categories: entropy encoding and source encoding. Entropy Encoding just manipulate bit streams without regard to what the bits mean. It is general, loss less, fully reversible technique, applicable to all data. Our example of entropy encoding is run-length encoding. In many Data Compression Shortest path in a Network Checking LAN, IPX & SPX Installation File Transfer using RS-232 C

kinds of data, strings of repeated symbols (bits, numbers, etc.,) are common. These can be replaced by a special marker not otherwise allowed in the data, followed by the symbol comprising the run, followed by how many times it occurred. If the special marker itself occurs in the data, it is duplicated (as in character stuffing). For example, consider the following string of decimal digits:

13

315000000000000845871111111111111635467400000076 If we now introduce A, as the marker and use two-digit numbers for the repetition count, we can encode the above digit string as 315A01284587A11316354674A00576 Here run-length encoding has cut the data string in half. Runs are common in multimedia. In audio, runs of zeros often

represent silence. In video, runs of the same color in shots of the sky, walls, and many flat surfaces can occur. All of these runs can be greatly compressed. 2. SHORTEST PATH IN A NETWORK The routing algorithm is that part of the network layer software responsible for deciding which output line an incoming packet should be transmitted on. Routing algorithms can be grouped into two major classes: nonadaptive and adaptive. Non-adaptive algorithms do not base their routing decisions on measurements or estimates of the current traffic and topology. Instead, the choice of the route to use to get from I to J (for all I & J) is computed in advance, offline, and downloaded to the routers when the network is booted. This procedure is sometimes called static routing. Adaptive algorithms, in contrast, change their routing decisions to reflect changes in the topology, and usually the traffic as well. Adaptive algorithms differ in where they get their information (e.g., locally, from adjacent routers, or from all routers), when they chance the routeds (e.g., every AT see, when the load

14

changes, or when the topology changes), and what metric is used for optimization (e.g., distance, number of hops, or estimated transit time). The concept of a Shortest Path deserves some explanation. One way of measuring path length is the number of hops. Another metric is the geographic distance in kilometers. However, many other metrics are also possible besides hops and physical distance. For example, each are could be labeled with the mean queuing and transmission delay for some standard test packet as determined by hourly test runs. With this graph labeling, the shortest path is the fastest path, rather than the path with the fewest arcs or kilometers. Several algorithms for computing the shortest path between two nodes of a graph are known. This one is due to Dijkstra (1959). Each node is labeled (in parenthses) with its distances from the source node along the best-known path. Initially, no paths are known, so all nodes are labeled eith infinity. As the algorithm proceeds and paths are found, the labels may change, reflecting better paths. A label may be either tentative or permanent. Initially, all labels are tentative, when it is discovered that a label represents the shortest possible path from the source to that node, it is made permanent and never changed thereafter. To illustrate how the labeling algorithm works, look at the weighted, undirected graph where the weights represent, for example, distance. We want to find the shortest path from Source to Destination. We start out by marking 1 in source node as permanent, indicated by a filled in circle. Then we examine, the distance to source. Whenever a node is relabeled, we also label it with the node from which the probe was made, so we can reconstruct the final path later. Having examined each of the nodes adjacent to source, we examine all the tentatively labeled nodes in the whole graph and make the one with the smallest label permanent. This one becomes the new working node.

15

We now start at B, and examine all nodes adajacent to it. If the sum of the label on B and the distance from B to the node being considered is less than the label on that node, we have a shortest path so the node is relabeled. After all the nodes adjacent to the working node have been inspected and the tentative labels changed if possible, the entire graph is searched for the tentatively labeled node with the smallest value. This node is made permanent and becomes the working node for the next round. We compute the shortest path starting at the terminal node, t rather than at the source node, s. Since the shortest path from t to s in an undirected graph is the same as the shortest path from s to t, it dose not matter at which end we begin (unless there are several shortest path, in which case reversing the search might discover a different one). The reason for searching backward is that each node is labeled with its predecessor rather than its successor. When copying, the final path into the output variable, path, the path is thus reversed. By reversing the search, the two effects cancel, and the answer is produced in the correct order. 3. CHECKING LAN,IPX, & SPX INSTALLATION Checking for LAN 1. 2. 3. 4. Initialise all register with 0xEA. Al register with 1 and BX register with 0. Invoke the function int86x with interrupt 0x21. Check the content of BX register. If 0, it is not a LAN, else it is a LAN.

IPX Installation Test 1. 2. 3. 4. Store 0x7900 to AX register. Invoke the function int86x with interrupt 0x21. Check the content of AL register. If 0xff, IPX is installed else not installed.

16

SPX Installation Test 1. 2. 3. 4. installed. Store 0x7900 to AX register. Invoke the function int86x with interrupt 0x21. Check the content of C flag. If it is 1, print SPX is installed and its details, else print SPX is not

4. FILE TRANSFER USING RS-232 C RS-232 C is a null modem physical layer standard. It is the third revision of the original RS-232 C standard. It must specify in detail the mechanical, electrical, functionsl and procedural interface. The mechanical specification is for a 9 pin connector. It is 21 m.m wide (screw center to screw center) with all other dimensions equally well specified. The top row has pins numbered 1 to 5 (left to right). The bottom row has pins numbered 6 to 9 (also left to right). The electrical specification for RS-232C is that a voltage more negative than 3 volts is a binary 1 and a voltage more positive then +5 volts is a binary 0. The functional specifications tell which circuits are connected to each of pins and what they mean.

1 2 3 7

1 2 3 7

System A Pin 1 is Protective Ground Pin 2 is to Transmit Data Pin 3 is to Receive Data Pin 7 is Common Return

System B

17

The procedural specification is the protocol that is the legal sequence of events. The protocol is based on action reaction pairs. The action-reaction pairs exist for all circuits as well. Limitations of RS-232C A Null modem looks like a short cable. The cable length between the two-end connector is up to 15 meters. Data rates p to 20 kbps are permitted. Supporting Language The C Language support the file transfer using RS-232 C between two systems Outportb(port,value) This function is used to transfer the value (data) to port. Inportb(port) This function is used to get the value(data) from the port.

18

SOLVED PROBLEMS IN JAVA LAB CYCLE 1


Write a Java program
1. 2. 3. 4. 5. To find the IP Address of the Local Host. To Send and Receive a Packet using UDP. To Send and Receive a Packet using TCP. To implement Lowercase to Uppercase Conversion (Client/Server). To send the password as a Packet from client and receive the related data from the Server. 6. To send the filename from Client and receive the content of the file from the Server. Using URL Using FileInputStream 7. To implement Chatting. 8. To implement JDBC Back End MS ACCESS Back End - ORACLE 9. To implement JDBC (Back End ORACLE) - DDL Commands 10. To implement JDBC (Back End ORACLE) DML Commands

19

Program No.: 1 //To find the IP Address of the LocalHost. import java.net.*; import java.io.*; public class inet { public static void main(String a[]) { try { InetAddress Inet = InetAddress.getLocalHost(); System.out.println(InetAddress.getLocalHost()); System.out.println(InetAddress.getByName("mca41")); System.out.println("Address : " +Inet.getHostAddress()); System.out.println("Name : " +Inet.getHostName()); } catch(UnknownHostException e) { System.out.println(e); } } }

20

Program No. 2 // To receive a packet from the client and send it backs - UDP // Server Side import java.net.*; import java.io.*; public class DatagramServer { public static void main(String args[]) throws Exception { //To create a datagram socket DatagramSocket Gs = new DatagramSocket(1234); //To create DatagramPacket objects to hold the packets DatagramPacket rp,sp; //To receive the packet from the client rp = new DatagramPacket(new byte[512],512); Gs.receive(rp); //To send the packet to the client sp = new DatagramPacket(rp.getData(),rp.getLength(),rp.getAddress(),rp.getPort()); Gs.send(sp); System.out.write (rp.getData(),0,rp.getLength()); } }

21

// To send a packet to the server and receive it back //Client Side import java.io.*; import java.net.*; public class DatagramClient { public static void main(String args[]) throws Exception { //To initialize host address and host port int hp = 1234; InetAddress hA = InetAddress.getByName("localhost"); //To create a datagram socket DatagramSocket Gs = new DatagramSocket(); //To create DatagramPacket objects to hold the packets DatagramPacket rp,sp; //To send a Packet to the server String mes = "Suguna"; byte buf[] = new byte[mes.length()]; mes.getBytes(0,mes.length(),buf,0); sp = new DatagramPacket (buf,buf.length,hA,hp); Gs.send(sp); //To receive the packet from the server rp = new DatagramPacket(new byte[512],512); Gs.receive(rp); System.out.write(rp.getData(),0,rp.getLength()); } }

22

Program No. 3 //StreamServer.java //To receive data from a stream client and send it back - TCP import java.io.*; import java.net.*; class StreamServer { public static void main(String args[]) throws Exception { String Data; // To create a stream server socket ServerSocket welsoc = new ServerSocket(8080); //To listen for a client connection Socket consoc = welsoc.accept(); //To create input and output streams and receiving streams DataInputStream fromclient = new DataInputStream (consoc.getInputStream()); DataOutputStream ToCnt=new DataOutputStream(consoc.getOutputStream()); //To receive data from client and send it back Data = fromclient.readLine(); ToCnt.writeBytes(Data+"\n"); //To print the data received from the client System.out.println ("From Client:" + Data); fromclient.close(); ToCnt.close(); welsoc.close(); } }

23

//StreamCleint.java // To send data to a stream server and receive it back import java.io.*; import java.net.*; class StreamClient { public static void main(String args[]) throws Exception { String OD = "suguna"; String ID; //To create a stream socket Socket clnSoc = new Socket ("localhost",8080); //To create input and output streams for sending and receiving streams DataOutputStream Toserver = new DataOutputStream (clnSoc.getOutputStream()); DataInputStream Fromserver = new DataInputStream (clnSoc.getInputStream()); //To send and receive data Toserver.writeBytes(OD+'\n'); ID = Fromserver.readLine(); //To print the data received from the server System.out.println ("From Server:" +ID); Toserver.close(); Fromserver.close(); } }

24

Program No. 4 // To receive the lowercase sentence from the client and send the equivalent uppercase sentence // server side import java.io.*; import java.net.*; class tcpserver { public static void main (String args[]) throws Exception { String lsent; String usent; ServerSocket serSoc = new ServerSocket(8080); Socket tSoc = serSoc.accept(); DataInputStream inFromClient = new DataInputStream(tSoc.getInputStream()); DataOutputStream outToClient = new DataOutputStream(tSoc.getOutputStream()); lsent = inFromClient.readLine(); usent = lsent.toUpperCase()+'\n'; System.out.println("Converted Sentence : " +usent); outToClient.writeBytes(usent); outToClient.close(); inFromClient.close(); serSoc.close(); } }

25

// To get a sentence in lowercase, send it to the server and to receive the equivalent uppercase // Client side import java.io.*; import java.net.*; class tcpclient { public static void main ( String args[]) throws Exception { String lcsent; String ucsent; Socket clientSoc = new Socket("localhost",8080); DataInputStream inputsent = new DataInputStream(System.in); DataOutputStream sentToserver=new DataOutputStream(clientSoc.getOutputStream()); DataInputStream outputsent = new DataInputStream(clientSoc.getInputStream()); System.out.println ("Enter a sentence in lowercase:"); lcsent = inputsent.readLine(); sentToserver.writeBytes(lcsent +'\n'); ucsent=outputsent.readLine(); System.out.println("Upper case Sentence: " +ucsent); sentToserver.close(); outputsent.close(); inputsent.close(); clientSoc.close(); } }

26

Program No. 5 // To receive the password from the client and send the data as a datagram packet //Server side import java.io.*; import java.net.*; public class udppasswordserver { public static void main (String[] args) { DatagramSocket sock = null; DatagramPacket recPack, sendPack; String userData; try { sock = new DatagramSocket(1234); recPack = new DatagramPacket (new byte[512],512); sock.receive(recPack); String revd ="Packet received from : " +recPack.getAddress()+","+recPack.getPort()+'\n'; System.out.println(revd); String buff = new String (recPack.getData(),0,recPack.getLength()); if (buff.equals("SS")) { userData = "You got connected with " + InetAddress.getLocalHost(); } else { userData = "Incorrect password Connection denied"; } byte sendBuff[] = new byte[userData.length()]; userData.getBytes(0,userData.length(),sendBuff,0); sendPack = new DatagramPacket(sendBuff,sendBuff.length,recPack.getAddress(),recPack.get Port()); sock.send(sendPack); } catch(SocketException e) { System.out.println("Error in Server" +e); } catch(Exception e){} } }

27

// To send the password as a datagram packet and receive the data from the sever // Client Side import java.io.*; import java.net.*; public class udppasswordclient { public static void main (String[] args) { //To create a datagram socket DatagramSocket sock = null; DatagramPacket recPack,sendPack; try { sock = new DatagramSocket(); InetAddress hostAddress = InetAddress.getByName("mca33"); DataInputStream userData = new DataInputStream(System.in); System.out.println ("Enter Password"); String userString = userData.readLine(); byte sendBuff[] = new byte[userString.length()]; userString.getBytes(0,userString.length(),sendBuff,0); sendPack = new DatagramPacket(sendBuff,sendBuff.length,hostAddress,1234); sock.send(sendPack); recPack = new DatagramPacket (new byte[512],512); sock.receive(recPack); System.out.write(recPack.getData(),0,recPack.getLength()); System.out.println("\n\n"); } catch (SocketException e) { System.out.println("Error in Server" + e); } catch(IOException e) { System.out.println ("Error in Server" + e); } } }

28

Program No. : 6 a // To receive the filename from the client and send the file as a datagram packet // Server Side import java.io.*; import java.net.*; public class Serverfilename { public static void main (String[] args) throws Exception { DatagramSocket sock = null; DatagramPacket recPack,sendPack,ErrPack; String userData; byte[] sendBuff = new byte[4000]; byte[] Errbuff = new byte[40]; recPack = new DatagramPacket (new byte[512],512); try { sock = new DatagramSocket(1234); // TO receive the filename sock.receive(recPack); System.out.println("Packet received from : " + recPack.getAddress()+","+recPack.getPort()+"\n"); String buffer = new String (recPack.getData(),0,recPack.getLength()); //To open the requested file and read the contents in the buffer contents File f = new File(buffer); String contents = " "; FileInputStream fis = new FileInputStream(f); for (int i=0; i<f.length();i++) contents += (char) fis.read(); //To convert contents to byte contents.getBytes(0,contents.length(),sendBuff,0); //To send the contents sendPack = new DatagramPacket (sendBuff,contents.length(),recPack.getAddress(),recPack.getPort()); sock.send(sendPack); } catch (FileNotFoundException e) { System.out.println("Requested File is nor Found in Server"); } catch(SocketException e) { System.out.println("Error in Server"+e);

29

} catch(IOException e) { System.out.println("Error in Server" + e); } } }

30

// To send the filename as a datagram packet and receive the contents of the file from the server //Client Side import java.io.*; import java.net.*; public class Clientfilename { public static void main (String[] args) { DatagramSocket sock = null; DatagramPacket recPack,sendPack; try { sock = new DatagramSocket(); InetAddress hostAddress = InetAddress.getByName("localhost"); DataInputStream userData = new DataInputStream(System.in); System.out.println("Enter Filename"); String userString = userData.readLine(); byte sendBuff[] = new byte[userString.length()]; userString.getBytes(0,userString.length(),sendBuff,0); // To send the filename to the server sendPack = new DatagramPacket (sendBuff,sendBuff.length,hostAddress,1234); sock.send(sendPack); //To receive the file or the error message and print it recPack = new DatagramPacket (new byte[4000],4000); sock.receive(recPack); String readString = new String (recPack.getData(),0,recPack.getLength()); System.out.println(readString); }catch (SocketException e) { System.out.println("Error in Server" + e); } catch(IOException e) { System.out.println("Error in Server" +e); } } }

31

Program No.: 6 b // Write a java program to display the content of specified URL or Website. import java.io.*; import java.net.*; public class urlcon { public static void main (String a[]) { try { URL url=new URL("file:///h:/sugunaraj/suguna.doc"); URLConnection ucon=url.openConnection(); System.out.println ("connection type: " +ucon.getContentType()); int len=ucon.getContentLength(); InputStream inp=ucon.getInputStream(); BufferedReader br=new BufferedReader (new InputStreamReader(inp)); String s = " "; while ((s=br.readLine()) !=null) { System.out.println(s); } } catch (IOException e) { System.out.println(e); } } }

32

Program No.: 7 //Chatting - Server side import java.io.*; import java.net.*; class chatserver { public static void main(String args[]) throws Exception { String receive; String send; ServerSocket welsoc = new ServerSocket(8080); Socket consoc = welsoc.accept(); DataInputStream fromclient = new DataInputStream (consoc.getInputStream()); DataOutputStream ToCnt=new DataOutputStream(consoc.getOutputStream()); DataInputStream inputsent = new DataInputStream(System.in); while (true) { receive = fromclient.readLine(); System.out.println ("From Client:" +receive); System.out.println ("Enter a sentence :"); send = inputsent.readLine(); ToCnt.writeBytes(send+'\n'); } } }

33

//chatting - Client side import java.io.*; import java.net.*; class chatclient { public static void main(String args[]) throws Exception { String send; String receive; Socket clnSoc = new Socket ("localhost",8080); DataOutputStream Toserver = new DataOutputStream (clnSoc.getOutputStream()); DataInputStream Fromserver = new DataInputStream (clnSoc.getInputStream()); DataInputStream inputsent = new DataInputStream(System.in); while (true) { System.out.println ("Enter a sentence :"); send = inputsent.readLine(); Toserver.writeBytes(send+'\n'); receive = Fromserver.readLine(); System.out.println ("From Server:" +receive); } } }

34

Program No.: 8 // a. To access the database using JDBC (Back End - MS ACCESS) import java.io.*; import java.sql.*; public class jdbc { public static void main (String a[]) { try { String url = "jdbc:odbc:cabss"; Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con = DriverManager.getConnection (url,null,null); Statement st = con.createStatement(); ResultSet rs = st.executeQuery ("select * from sug"); while (rs.next()) { System.out.println ("name : " +rs.getString ("no")); System.out.println ("rollno : "+rs.getString ("name")); System.out.println ("age : " +rs.getString ("esal")); } } catch (Exception e) { System.out.println(e); } } } // b. Access database using JDBC - ORACLE import java.sql.*; import java.net.*; public class sql{ public static void main(String args[]) throws Exception { String url="jdbc:odbc:javaora"; Try { Class.forName("sun.jdbc:odbc:JdbcOdbcDriver"); Connection con=DriverManager.getConnection(url,"scott","tiger"); Statement st=con.createStatement(); ResultSet rs=st.executeQuery("select * from sugemp;");

35

while(rs.next()) { System.out.println ("name : " +rs.getString ("name")); System.out.println ("regno : " +rs.getString ("regno")); System.out.println ("Salary : " +rs.getString ("sal")); } } catch(Exception e){System.out.println("Error"); } } }

36

Program No.: 9 // DDL Command 1 : Create Table - ORACLE import java.sql.*; import java.io.*; public class jdbccreatetable { public static void main (String args[]) throws Exception { try { String url = "jdbc:odbc:javaora"; Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con = DriverManager.getConnection(url,"scott","tiger"); Statement stmt = con.createStatement(); stmt.executeQuery("create table studet (name varchar2(10),address varchar2(10));"); }catch (SQLException e) { System.out.println(e); } } } // DDL Command2 : Alter import java.sql.*; import java.io.*; public class sqlalter { public static void main(String args[]) { try { String url = "jdbc:odbc:sub1"; Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con = DriverManager.getConnection (url,"scott","tiger"); Statement stmt = con.createStatement(); stmt.executeUpdate ("alter table studmarks add (mark3 number(3))"); ResultSet rs = stmt.executeQuery ("Select * from studmarks"); while (rs.next()) { System.out.println("rollno : " +rs.getString("rollno"));

37

System.out.println("name : " +rs.getString("name")); System.out.println("mark1 : " +rs.getString("mark1")); System.out.println("mark2 : " +rs.getString("mark2")); System.out.println ("\n"); } }catch (Exception e) { System.out.println (e.getMessage()); } } } // DDL Command3 : Drop import java.sql.*; import java.io.*; public class sqldrop { public static void main(String args[]) { try { String url = "jdbc:odbc:sub1"; Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con = DriverManager.getConnection (url,"scott","tiger"); Statement stmt = con.createStatement(); stmt.executeUpdate ("drop table studmarks"); }catch (Exception e) { System.out.println (e.getMessage()); } } }

38

Program No.: 10 // DML Command 1 : Insertion import java.sql.*; import java.io.*; public class sqlinsertion { public static void main(String args[]) { try { String url = "jdbc:odbc:sub1"; Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con = DriverManager.getConnection (url,"scott","tiger"); Statement stmt = con.createStatement(); stmt.executeUpdate ("insert into studmarks values ('019061','sheelu',90,98)"); ResultSet rs = stmt.executeQuery ("Select * from studmarks"); while (rs.next()) { System.out.println("rollno : " +rs.getString("rollno")); System.out.println("name : " +rs.getString("name")); System.out.println("mark1 : " +rs.getString("mark1")); System.out.println("mark2 : " +rs.getString("mark2")); System.out.println ("\n"); } }catch (Exception e) { System.out.println (e.getMessage()); } } }

// b. DML Command 2 : Deletion import java.sql.*; import java.io.*; public class sqldeletion { public static void main(String args[]) {

39

try { String url = "jdbc:odbc:sub1"; Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con = DriverManager.getConnection (url,"scott","tiger"); Statement stmt = con.createStatement(); stmt.executeUpdate ("Delete from studmarks where rollno=018001"); ResultSet rs = stmt.executeQuery ("Select * from studmarks"); while (rs.next()) { System.out.println("rollno : " +rs.getString("rollno")); System.out.println("name : " +rs.getString("name")); System.out.println("mark1 : " +rs.getString("mark1")); System.out.println("mark2 : " +rs.getString("mark2")); System.out.println ("\n"); } }catch (Exception e) { System.out.println (e.getMessage()); } } }

// c. DML Command 3 : Updation of an Exisiting Record import java.sql.*; import java.io.*; public class sqlupdation { public static void main(String args[]) { try { String url = "jdbc:odbc:sub1"; Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con = DriverManager.getConnection (url,"scott","tiger"); Statement stmt = con.createStatement(); stmt.executeUpdate ("Update studmarks set mark1=mark1-5 where rollno=018008"); ResultSet rs = stmt.executeQuery ("Select * from studmarks"); while (rs.next()) { System.out.println("rollno : " +rs.getString("rollno")); System.out.println("name : " +rs.getString("name"));

40

System.out.println("mark1 : " +rs.getString("mark1")); System.out.println("mark2 : " +rs.getString("mark2")); System.out.println ("\n"); } }catch (Exception e) { System.out.println (e.getMessage()); } } }

41

SOLVED PROBLEMS IN C LAB CYCLE 2

Write a C/C++ program 1. to implement data compression and decompression techniques. 2. to find shortest path in a network. 3. to check LAN, IPX, & SPX installation. 4. to transfer a file using RS232C Interface.

42

Program No.: 1 // Data compression and Decompression Using Runlength Encoding #include<stdio.h> #include<conio.h> #include<process.h> char file1[20],file2[20],a,b,c,s,ch; int I,j, ct1,ct2,ct,n; FILE *f1, *f2; Void compress() { printf(enter the file to compress); scanf(%s, file1); for(I=0;file1[I] !=.;I++) file2[I]=file1[I]; file2[I]=\0; strcat(file2,.cmp); f1=fopen(file1,r); f2=fopen(file2,w); if(f1==0) printf(error in opening %s,file1); else a=getc(f1); while(a != EOF) { s=#; n=1; while((b=getc(f1)) == a &&b != EOF) n++; if(n>3) { if(n >=10) fprintf(f2,%c%c%d,s,a,n); else fprintff(f2,%c%c%c%d,s,a,o,n); } else { for(I=0;I<n;I++) fprintf(f2,%c,a); } a=b;

43

} printf(%s is compressed and stored in %s, file1,file2); fclose(f1); fclose(f2); f1=fopen(file1,r); f2=fopen(file2,r); printf( original contents); while ((c=getc(f1)) != EOF) putchar; printf(compressed contents); while((c=getc(f2)) != EOF) putchar; printf(compression is successful); } fcloseall(); } void decompress() { strcpy(file1,file2); for(I=0;file1[I] != .;I++) file2[I]=file1[I]; file2[I] = \0; strcat(file2,.dmp); f1=fopen(file1,r); f2=fopen(file2,w); if(f1== 0 || f2 ==0) printf(error); else { while((a=getc(f1)) != EOF) { if(a == #) { ch=getc(f1); ct1=fgetc(f1)-0; ct2=fgetc(f1)-0; ct=((ct1*10)+ct2); for(I=0;e<(int)ct;I++) fprintf(f2,%c,ch); } else fprintf(f2,%c,a); } printf(%s is decompressed and stored is %s ,file1,file2); fclose(f2);

44

printf(decompressed contents); f2=fopen(file2,r); while((c=getc(f2)) != EOF) putchar; printf(decompression is successfule); } fcloseall(); } void main() { int choice; clrscr(); printf(compression and decompression ); while(1) { printf(1.compression 2. decompression 3. exit ); printf (enter your choice); scanf(%d,&choice); switch(choice) { case 1 : compress(); break; case 2 : decompress(); break; case 3 : exit(0); default : printf(wrong choice); } } }

45

Program No.: 2 // FINDING SHORTEST PATH IN A NETWORK #include <stdio.h> #define INFINITY 10000 #include <conio.h> #include <process.h> int v1,v2,wt,I,j,n,e,c,s1,d1,cost,t; int min,k, dist[10][10], path[30]; void shorts() { cost =0; for(I=0;I<5;I++) { for(j=0;j<5;j++) dist[I][j]=0; } } void get() { printf(enter the number of nodes); scanf(%d,&n); printf (enter the number of edges); scanf(%d,&e); printf(enter the edges and their weights); for(I=0;I<e;I++) { scanf(%d%d%d,&v1,&v2,&wt); dist[v1][v2]=wt; dist[v2][v1]=wt; } } void source() { printf(enter the source code); scanf(%d,&v1); printf(enter the destination code); scanf(%d,&v2); s1=v2; t=v1; cost=0;

46

struct state { int pre; int len; int flag; }s[20]; struct state *p; for(p=&s[1];p<=&s[n];p++) { p->pre=-1; p->len=INFINITY; p->flag =0; } s[t].len=0; s[t].flag=1; k=t; while(k!=s1) { for(I=1;I<=n;I++) { if((dist[k][I] != 0) && (s[I].flag==0)) { if(s[k].len+dist[k][I]<s[I].len) { s[I].pre=k; s[I].len=s[k].len+dist[k][I]; } if(I==s1) { if(t!=k) printf(%d%d%d%d,t,k,I,s[I].len); else printf(%d%d%d,k,I,s[I].len); } } } k=0; min=INFINITY; for(I=1;I<=n;I++) { if((s[I].flag==0)&&(s[I].len<min)) { min=s[I].len; k=I; } }

47

s[k].flag=1; } c=0; k=s1; while(k>=0) { path[c++]=k; k=s[k].pre; } I=0; While(I<c-1) { cost=cost+dist[path[I]]path[I+1]]; I++; } } void disp() { printf(shorthest path); for(I=c-1;I>=0;I--) { printf(%d,path[I]); printf(\t); } printf(the cost is %d ,cost); getch(); } void main() { int ch; clrscr(); shorts(); while(1) { printf(1. graph details 2. get the source and destination node 3. display 4. exit); printf(enter the choice); scanf(%d,&ch); switch(ch) { case 1: get(); break; case 2: source(); break;

48

case 3: disp(); break; case 4: exit(0); } } }

49

Program No.: 3 // FILE TRANSFER USING RS_232C // /* SENDER */ #include<stdio.h> #include<conio.h> #include<process.h> #include<dos.h> #include<io.h> void main() { clrscr(); int port =0x3f8,I=0; char ch,ch1,ch2,fn[20]; FILE *f1; Printf(connecting); While((ch=inportb(port))!=i) { printf(.); delay(600); } printf(connection established); outportb(port,^); while((inportb(port))!=^) { if((ch1=inportb(port)!=i) { fn[I++]=ch1; delay(300); } } fn[I]=\0; printf(filename %s,fn); f1=fopen(fn,r); if(f1!=NULL) { while((ch=fgetc(f1))!=EOF) { outport(port,ch); printf(%c,ch); delay(300); } fclose(f1);

50

delay(200); outportb(port,@); printf(file transfer complete); } else { printf(file not found); delay(300); outportb(port,~); exit(0); } getch(); }

51

/* TRANSFER USING RS232 - RECEIVER */ #include<stdio.h> #include<conio.h> #include<dos.h> #include<string.h> #include<process.h> void main() { int port=0x3f8,h,I=0; char c,x,d[30],fname[100],ch,b,val=i; FILE *f1; Clrscr(); Outportb(port,val); Printf(data send); Delay(300); Ch=inportb(port); If(ch==^) { printf(%c,ch); printf(enter the filename); scanf(%s,fname); I=0; While(fname[I]!=\0) { outportb(port,fname[I]); delay(250); I++; } outportb(port,^); f1=fopen(fname,w); delay(30); while((ch=inportb(port))!=@) { if(ch==~) { printf(file does not exist); exit(0); } else { fputc(ch,f1); printf(%c,ch); delay(300); }

52

} fcloseall(); printf(transferred successfully); getch(); } }

53

Program No.: 4 /* CHECKING FOR LAN IPX SPX CONNECTIONS #include<stdio.h> #include<conio.h> #include<dos.h> void main() { union REGS regs; int ch; struct SREGS sregs; int j; char reply[50]; clrscr(); do { printf(1.lan 2. ipx 3. spx ); printf(enter the choice); scanf(%d,&ch); switch(ch) { case 1: regs.h.ah=oxea; regs.h.a1=1; regs.x.bx=0; sregs.es=FP_SEG((void far*)reply); regs.x.dx=FP_OFF((void far*)reply); int86x(0x21,&regs,&sregs); if(regs.x.bx!=0) printf(system is working with lan); else printf(system is not working with lan); break; case 2: regs.x.ax=0x7900; regs.h.al=0xff; int86x(0x21,&regs,&regs,&sregs); if(regs.h.a1!=0xff) printf(ipx is installed); else printf(ipx is not installed); break; case 3: */

54

regs.x.ax=0x7900; regs.h.al=0xff; int86x(0x21,&regs,&regs,&sregs); if(regs.x.cflag==1) printf(spx is installed); else printf(spx is not installed); break; } printf(press 1 to continue); scanf(%d,&j); }while(j==1); getch(); }

55

Assignment Problems

1. Remote Command Execution. 2. Simulation of HDLC Protocol. 3. Simulation of X.25 Protocol. 4. Solve any two Network related problems of your choice.

56

You might also like