Socket Programming


UDP and TCP Sockets in Java.
A simple Client Server Program in Java

AIM:
The aim of the assignment is :
A : become familiar with datagram socket.
B : become familiar with TCP sockets and to implement a simple application level protocol.

Socket:
Sockets provide an interface for programming networks at the transport layer.
Network communication using Sockets is very much similar to performing file I/O In fact, socket handle is treated like file handle.
The streams used in file I/O operation are also applicable to socket-based I/O
Socket-based communication is programming language independent.
That means, a socket program written in Java language can also communicate to a program written in Java or non-Java socket program

Socket Communication :
A server (program) runs on a specific computer and has a socket that is bound to a specific port. The server waits and listens to the socket for a client to make a connection request.If everything goes well, the server accepts the connection. Upon acceptance, the server gets a new socket bounds to a different port. It needs a new socket (consequently a different port number) so that it can continue to listen to the original socket for connection requests while serving the connected client

UDP:
UDP (User Datagram Protocol) is a protocol that sends independent packets of data, called datagrams, from one computer to another with no guarantees about arrival.
Example applications:
Clock server
Ping

TCP:
TCP (Transport Control Protocol) is a connection-oriented protocol that provides a reliable flow of data between two computers.
Example applications:
HTTP
FTP
Telnet
Understanding Ports:

The TCP and UDP protocols use ports to map incoming data to a particular process running on a computer.
Port is represented by a positive (16-bit) integer value
Some ports have been reserved to support common/well known services:
ftp 21/tcp
telnet 23/tcp
smtp 25/tcp
login 513/tcp
User level process/services generally use port number value >= 1024

Sockets and Java Socket Classes
A socket is an endpoint of a two-way communication link between two programs running on the network. A socket is bound to a port number so that the TCP layer can identify the application that data destined to be sent.Socket – for implementing a clientServerSocket – for implementing a server

A simple server (simplified code)

// Server.java
// Sockets upload application - the Server component.
//
// Created by Duncan Gough on Wed Nov 06 2002.
// Copyright (c) 2002 Duncan Gough/suttree. All rights reserved.
//
// This is the server that will run forever on your machine. Once it hears an incoming // connection, on PORT, it writes it to the file specified by OutputFilename, and
// that's about it.

import java.lang.*;
import java.io.*;
import java.net.*;

class Server {

static final String OUTPUTFILENAME = "C:\\receivedData";
static final int PORT = 5791;

public static void main(String args[]) {

System.out.println("New server running...\n\n");

// Infinite loop, innit
while ( true ) {

try {
//Create a socket
ServerSocket srvr = new ServerSocket(PORT);
Socket skt = srvr.accept();

//Create a file output stream, and a buffered input stream
FileOutputStream fos = new FileOutputStream(OUTPUTFILENAME);
BufferedOutputStream out = new BufferedOutputStream(fos);
BufferedInputStream in = new BufferedInputStream( skt.getInputStream() );

//Read, and write the file to the socket
int i;
while ((i = in.read()) != -1) {
out.write(i);
//System.out.println(i);
System.out.println("Receiving data...");
}
out.flush();
in.close();
out.close();
skt.close();
srvr.close();
System.out.println("Transfer complete.");
}
catch(Exception e) {

System.out.print("Error! It didn't work! " + e + "\n");
}

//Sleep...
try {
Thread.sleep(1000);
} catch (InterruptedException ie) {
System.err.println("Interrupted");
}

} //end infinite while loop
}
}

A simple client (simplified code)
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.filechooser.*;
import javax.swing.border.*;
import java.lang.*;
import java.net.*;

public class Client extends JFrame implements ActionListener, ItemListener {
static private final String newline = "\n";
JScrollPane scrollPane;

public Client() {
super("Sockets upload application");

//Use the system default look and feel (default to Java LAF otherwise)
try{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch(Exception e){
System.out.println("Can't get system look and feel, resorting to default.");
}

//Create the log first, because the action listeners need to refer to it.
final JTextArea log = new JTextArea(5,55); // 5,60
log.setMargin(new Insets(5,5,5,5));
log.setEditable(false);
JScrollPane logScrollPane = new JScrollPane(log);

//Create a file chooser
final JFileChooser fc = new JFileChooser();

//Create the open button
ImageIcon openIcon = new ImageIcon("open.gif");
JButton openButton = new JButton("Open", openIcon);
openButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int returnVal = fc.showOpenDialog(Client.this);

log.append("Opening - ");

if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();

log.append(file.getName() + newline);

//Create a client, give it the chosen filename, and send the data across
Client_socket client = new Client_socket();
if (client.send(file.getPath().toString()))
log.append("Success." + newline);
else
log.append("Failure." + newline);
}
}
});

//Show the menu ;-)
this.showMenu();

//For layout purposes, put the buttons in a separate panel
JPanel buttonPanel = new JPanel();
buttonPanel.add(openButton);

//Add the buttons and the log to the frame
Container contentPane = getContentPane();
GridBagLayout gridbag = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
contentPane.setLayout(gridbag);

c.fill = GridBagConstraints.VERTICAL;
c.weightx = 0.0;
c.gridx = 0;
c.gridy = 0;
gridbag.setConstraints(buttonPanel, c);
contentPane.add(buttonPanel);

c.weightx = 0.0;
c.gridwidth = 60;
c.gridx = 0;
c.gridy = 1;
gridbag.setConstraints(logScrollPane, c);
logScrollPane.setBorder(new LineBorder(Color.black));
contentPane.add(logScrollPane);
}

public void showMenu() {
JMenuBar menuBar;
JMenu menu;
JMenuItem menuItem;

//Create the menu bar.
menuBar = new JMenuBar();
setJMenuBar(menuBar);

//Build the first menu.
menu = new JMenu("File");
menu.setMnemonic(KeyEvent.VK_F);
menu.getAccessibleContext().setAccessibleDescription("File menu");
menuBar.add(menu);
menuItem = new JMenuItem("Exit",KeyEvent.VK_E);
menuItem.addActionListener(this);
menu.add(menuItem);

//Build second menu in the menu bar.
menu = new JMenu("Help");
menu.setMnemonic(KeyEvent.VK_H);
menu.getAccessibleContext().setAccessibleDescription("Help menu");
menuBar.add(menu);
menuItem = new JMenuItem("About",KeyEvent.VK_A);
menuItem.addActionListener(this);
menu.add(menuItem);
menuItem = new JMenuItem("Help",KeyEvent.VK_H);
menuItem.addActionListener(this);
menu.add(menuItem);
}

public void actionPerformed(ActionEvent e) {
JMenuItem source = (JMenuItem)(e.getSource());

if (source.getText().equals("Exit")) {
System.exit(0);
} else if (source.getText().equals("About")) {

JFrame about_frame = new About();
about_frame.addWindowListener(new WindowAdapter() {});
about_frame.pack();
about_frame.setSize(400,135);
about_frame.setVisible(true);

} else if (source.getText().equals("Help")) {
JFrame help_frame = new Help();
help_frame.addWindowListener(new WindowAdapter() {});
help_frame.pack();
help_frame.setSize(400,400);
help_frame.setVisible(true);
}
}

public void itemStateChanged(ItemEvent e) {}

public static void main(String[] args) {
JFrame frame = new Client();

frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});

frame.pack();
frame.setSize(425,185);
frame.setVisible(true);
}

}

0 comments:

Post a Comment

 

NBA Live Streaming. Copyright 2008 All Rights Reserved Revolution Two Church theme by Brian Gardner Converted into Blogger Template by Bloganol dot com | Distributed by Blogger Templates Blog