You are on page 1of 41

Java Networking

• Networking in java is possible with the help of • Protocols: • Set of rules [for communication between computers in network] is called protocol. • Java networking is possible with TCP/IP protocol. • HTTP [ Hyper Text Transfer Protocols]: It enables interaction with the internet. • FTP [File Transfer Protocol]: It enables transfer of files between computers. • SMTP[Simple Mail Transfer Protocol]: It provides email facility. • NNTP[Network News Transfer Potocol]: Helps in sharing the news in the internet.

•A socket is one endpoint of a two way communication link between two programs running on the network. •An endpoint is a combination of an IP address and a port number. Every TCP connection can be uniquely identified by its two endpoints. That way you can have multiple connections between your host and the server. •TCP/IP protocol helps for communication. •IP provides the address of the Socket.

TCP/IP Sockets: • TCP/IP Sockets implements bidirectional connection between hosts on the internet. •Using this protocol, sockets are used for data communication. •Types : a) Server Socket b) Client Socket •Using Server Socket Class, the server waits for the client to make connection. •Using Client Socket Class, client connects to the server.

Socket Class: • A socket object establishes connection between client and server. Constructors of Socket Class: 1. Socket s = new Socket (String hostname, int port) 2. Socket s = new Socket (Inet Address a, int port)
Methods of Socket Class: 1.InetAddress,getInetAddress(): It returns InetAddress associated with socket object. getPort(): It returns remote port to which this socket object is conneted. getLocalport(): It returns the local port to which the socket object is connected.

4.InputStream,getInputStream(): It returns the InputStream associated with its socket. 5. OutputStream,getOutputStream(): It returns the OutputStream associated with its socket. 6.Void close() : It closes both InputSteam & OutputStream. ServerSocket Class: • A ServerSocket object waits for the client to make a connection. Methods of ServerSocket: • Same methods of Socket class and has one more method accept() which waits for a client to initiate communications. Constructors of ServerSocket Class: 1. Socket ss = new ServerSocket (int port) 2. Socket ss = new ServerSocket (int port,int maxque)

If not. proxy server gets content of those web server’s popular pages that provides faster access to those pages to the clients. which do not have such restrictions. and a real server. • When clients have some restrictions to connect to the server. such as a Web browser. it forwards the request to the real server. It intercepts all requests to the real server to see if it can fulfill the requests itself. . the client would connect to a proxy server. • Web When popular web site is used by hundreds of users.Proxy Servers: • A server that sits between a client application.

URL [ Uniform Resource Locator]: • URL is the address of a web page on the world wide web. .org/. http://en. SMTP. Components Of URL: • Protocol • IP address • Port Number • Actual file path Protocol: HTTP . NNTP. • URL helps in locating files using their address on the net. FTP or GOPHER IP Addr : It is delimited on the left by // and on the right by / or Colon. e.wiktionary.g.

• • • Third component Port is optional. URL u = new URL(URL urlobj. URL u = new URL(String Protocolname. URL u = new URL(String Protocolname. Last component specifies the actual Path) 4. Ex: http://www.html PROTOCOL HOSTNAME PORT NO.String urlspecifier) . ACTUAL FILE PATH Constructors: 1. URL u = new URL(String urlname) 2.String hostname.String hostname) 3.

2. getFile() : Returns the path of file specified in URL. getport() : Returns Port Number in URL. getHost(): Returns hostname specified in URL 3. openStream() : Open the file specified in the URL. .Methods of URL: 1. URL Connection: • This class provides methods to know more about the remote resource. 4.

Datagram Classes: 1. 4. getLastModified: Returns last modified date of object and zero if not known. • It is less reliable than communicating using TCP/IP. . 2. represents an entire communication. 3. getContentType(): Returns content type and returns null if not known. OpenConnection : It returns a URLConnection object associated with URL object. Datagram: • Datagram is a packet. DatagramPacket : This class acts as data container. 2. getContentLength() : Returns length of content and -1 if no known. DatagramSocket : This class used to send or receive datagrampackets.Methods of URLConnection: 1.

DatagramSocket Class: Methods: 1. • It supports various controls[Ex:Scroll bars. . and also can create stand alone windows GUI applications. Close() : Closes the Socket Connection. • AWT classes present in java.awt package. Methods of AWT Class: Add() : To add a control in a window Ex : add (Component Obj Remove() : To remove control from window. Receive(DatagramPacket p) : Receives the given datagram packet. 3. Send(DatagramPacket d) : Dispatches the datagram packet 2.Push buttons etc] • It supports applet windows. AWT Classes: • It provides support for applets.

Text .AWT Controls: Button : Creates push button control Canvas: A blank window Checkbox : Creates a checkbox control CheckboxGroup : Creates group of checkbox control Color : Gives various colours Cursor : Encapsulates a bitmapped cursor Dialog : Creates a dialog window Font : Gives Font window Label : It Creates a label List. Scrollbar. Menu. Menubar.

AWT Subsystems: Subsystems of AWT supports development of GUI. Event handling that allows user to interact with the application. Panels. Buttons and TextFields. & Dialogs. . Components such as Labels. Containers such as Frames. Layout managers that control the display. • • • • • Graphics primitives that allows drawing lines & images.

drawBytes(byte[] offset.Graphics Class: This class resides in java. .int y):Draws the text by the specified byte x. Methods: 1. drawChars(char[] length. data : data to be drawn offset : starting offset of data length : the number of bytes that are drawn x : x coordinate y : y coordinate 2.awt y):Draws text given by specified character length.

int height. fillOval((int x1.y1:Starting point height) 9. 6. fillRect(int height) .int height1) height) x. drawLine(int width.y1 – top left corner coordinates of the rectangle. y1. drawRoundREct(int x1. drawRect(int height) y1. drawString( String y1.y2:Ending point coordinates height1) 7. drawOval((int x1. fillRoundRect(int y2) y):Draws text given by the specified string.

Font Class: This class represents fonts. . int size): Creates new Font from specified name. Static int PLAIN : Represents plain font style. Constants: Static int BOLD : Represents bold font style. int style. Static int ITALIC : Represents italic font style. style and size. Constructor: Font(Stirng name.

.Methods: void setFont(Font f): Sets text to the specified font. int getSize() : Returns the current font size. setForeground() : Sets foreground color of an applet. setBackground(): Sets background color of an applet. int getStyle() : Returns the current font style. boolean isPlain() : Returns true if the font is plain boolean isBold() : Returns true if the font is bold boolean isItalic() : Returns true if the font is italic Color Class: Methods: setColor(): Sets specified color of an object.

• An EventListener interface defines one or more methods that are to be invoked by the event source. Types of event handling: It is divided into low level and semantic events. • When an event is fired. Low-level Event: It represents low level input or window system occurrence.Events: • In an interactive environment. • An EventSource is an object that fires events. the AWT generates an event and communicates it to event handlers. the program respond to actions performed by user. it is received by one or more listeners. • When user initiates an action. .

moved etc) • FocusEvent(Component got focus.mouse move) • ContainerEvent • WindowEvent Low level Event Listeners: • • • • • • • ComponentListener ContainerListener FocusListener KeyListener WindowListener MouseListener MouseMotionListener .key release) • MouseEvent(mousedown.Low level event classes: • ComponentEvent (Component resized.lost focus) • InputEvent • KeyEvent(Key press.

Semantic Events: • ActionEvent (do a Command) • AdjustmentEvent ( Value was adjusted) • ItemEvent ( item state has changed) SemanticListener: • ActionListener • AdjustmentListener • ItemListener • TextListener MouseEvents: • These are generated whenever a mouse is moved. etc. . pressed. clicked. released.

public void mouseReleased(MouseEvent e). } . public void mousePressed(MouseEvent e). public void mouseExited(MouseEvent e). public void mouseEntered(MouseEvent e).MouseListeners: • MouseListener Interface • MouseMotionListener Interface Definition of MouseListener Interface: Public interface MouseListener { public void mouseClicked(MouseEvent e).

public void mouseMoved(MouseEvent e). } .Definition of MouseMotionListener Interface: Public interface MouseMotionListener { public void mouseDragged(MouseEvent e). public void KeyTyped(KeyEvent e). public void KeyReleased(KeyEvent e). Definition of KeyListenerInterface: Public interface KeyListener { public void KeyPressed(KeyEvent e). } Keyboard Events: These are generated on pressing or releasing a key.

User Interface Components: • Container Class : Container controls can contain other AWT components. label etc. Containers: Panel Container Frame Window Dialog . • User Interface Component Class : It includes components like button.

User Interface Components: Label Button Checkbox Component TextComponent TextArea TextField Choice List Scrollbar .

Button : • The button is similar to a push button in any other GUI.Constructs a button with no label. Button(String label) . .Returns the label of the button. getLabel() . • Clicking a button generates an action event. • Constructors: Button() . Methods : addActionListener(ActionListener l) – Adds the specified action listener to receive action events from the corresponding button.Constructs a button with a specified label. setLabel(String Label) – Sets the label of the button to the specified label.

• Clicking on it can change the state of the check box. .addActionListener(this). checkbox(string Label) – Creates a check box with the specified label. b1. getState() – gets the state of the check box. Methods: getLable() – gets the name of the check box. CheckBox: • Check Boxes have dual state: checked and unchecked. • Constructor: checkbox() – Creates a check box with no label. setLable(String Label) .(ON or OFF State) setState(Boolean State) – sets the state of the checkbox.Sets the label of the checkbox to the specified value.How to create a Button: Button b1 = new Button(“OK”) add(b1).

List: It displays list of items. Constructors: List() – Creates a new scrolling list of items. List(int row) – Creates a new scrolling list of items with the specified number of visible lines. . so that the user can choose one or more items.

• getItem(int index) – gets the item at the specified index. • Add(String item. . int index) – Adds the item at the specified position.Methods: • Add(String item) – Adds the specified item at the end of the scrolling list. • getItemCount() – Gets the number of items in the list. • getItems() – gets all items from the list.

Constructor: TextField() – Constructs a new text field.Constructs a new text field initialized with the specified text.TextField: It accepts text input(small piece of information) from the user. Methods: setText(String t) – sets the text. . TextField(String text) .

int pos) – Inserts the string at the specified positions. insert(String s.Constructs a new text Area. TextArea(String Text) .Constructs a new text area with the specified text. Methods: append(String s) – Appends the given text with the text area content. . Constructors: TextArea() .TextArea: Similar to text field except that it can handle large amount of text.

.Layout Managers: • Layout managers are used to position the components in a container. Types:  FlowLayout  BorderLayout  GridLayout  GridBagLayout  CardLayout FlowLayout:  It is a simple layout manager that works like a word processor.

FlowLayout(int align) 3. getHgap():Gets horizontal gap between components 3.Constructors of FlowLayout: 1. getAlignment() : Gets the alignment for the layout. SetAlignment(int align): Sets the alignment 5. setVgap(int vgap):Sets the vertical gap .int hgap) Methods of FlowLayout: 1. FlowLayout(int align. setHgap(int hgap):Sets the horizontal gap 6. FlowLayout() : vgap. getVgap():Gets vertical gap between components 4. 2.

3. . GridLayout() : 2. getRows():Gets the number of rows of layout. getVgap():Gets vertical gap of the layout. setColumns(int cols) : sets the number of columns to the specified no. 5. vgap) Methods of FlowLayout: 1. getHgap():Gets horizontal gap of the layout. cols) 3.Grid Layout: • It lays out components in rows and columns. • All components in a grid layout are of same size. setRows():Sets the number of rows to the specified value. GridLayout(int rows. getColumns() : Gets the number of columns of layout.. GridLayout(int rows. Constructors of GridLayout: 1. setHgap(int hgap):Sets the horizontal gap to the specified value. 7. 8. setVgap(int vgap):Sets the vertical gap to the specified value. hgap.

BorderLayout(int hgap. getVgap(): Returns vgap b/w components 3. getHgap(): Returns hgap b/w components 2. BorderLayout() : Creates BorderLayout with no gap 2. Methods of Border Layout: 1. Constructors of Border Layout: 1.South. setVgap(int vgap) : Sets the vgap b/w components . • The placement of the component is specified as being North.Border Layout: • Components are placed on the border of a vgap): Creates BorderLayout with the specified hgap & vgap b/w components.East and West. setHgap(int hgap) : Sets the hgap b/w components 4.

[default height.GridBagLayout: • Divides a container into a grid of equally sized cells • Component can occupy more than one cell. gridheight specify width & height of the copmonent. width is 1] . Y coordinates. • Gridwidth.if needed • Total area occupied by a component is display area • Location of each component is specified by X.

1.BOTH: Component is stretched in both directions. 4.NONE : The size of the Component remains unchanged. 2.VERTICAL : Component is stretched Vertically. 3.• We can adjust the size of the component using. . GridBagConstraints.GridBagConstraints. GridBagConstraints.HORIZONTAL : Component is stretched horizontally. GridBagConstraints.

GridBagConstraints. GridBagConstraints.EAST 4. GridBagConstraints.NORTH 3. GridBagConstraints.NORTHEAST 7.SOUTHWEST 9.• The position of the component is specified as.NORTHWEST . GridBagConstraints.SOUTHEAST 8.WEST 6. GridBagConstraints. GridBagConstraints.SOUTH 5. GridBagConstraints. 1. GridBagConstraints.CENTER 2.

Card Layout : • It allows only one of its components to be visible at a time. • CardLayout is controleed by a combo box. . • The state of combo box determines which panel is displayed by the CardLayout.

Menu Bar .Menus: • Java’s AWT provides number of menu component classes to easily build & manage menus. . Menubar mb = new Menubar(). • The menu elements are.Menu Item Menubar Class: • Menu bar is the top most menu element displayed along the top of the window. • To create menubar.Menu . .

Add menu to a menubar.Menu Class: • It is used to implment pull down menu • To create a menu.add(menuitem1). mb. m. 3. 1. 2. Construct a new instance of menu class. . Add menu items to the newly constructed menu using add() method.add(m).add(menuitem2). Menu m = new Menu(“File”). m.

MenuItem m11.m2. use the following constructor MenuItem mitem = new MenuItem(“Open”) • To add menuitem to a menu. . Mb = new MenuBar(). setMenuBar(mb).add(mitem) Ex: MenuBar mb. m.MenuItem Class: • To create a menu item. Menu m1.m12.m13.

m2 = new Menu(“Edit”).add(m13). m12=new MenuItem(“Save”). m11=new MenuItem(“New”).add(m12).add(m2).add(m1). m13=new MenuItem(“Cut”). . M2. mb. mb. m1.m1 = new Menu(“File”).add(m11). m1.