Experiment 5
Networking
1, Objectives
1) Manipulating URL
2) Client/server interaction with stream socket connections
3) Connectionless client/server interaction with datagrams
2, Contents
(Copy the results or source codes after each exercise. Rename this document as “Id – Name.doc” and hand in it onto yvsou.com. )
1) Read a remote file
Create a URL object to connect to the web page http://www.zstu.edu.cn/Col/Col16/Index.aspx. Read this web page with an input stream and find all the addresses of the pictures in this page.
The framework looks as follows:
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
public class ReadUrlResource {
public static void main(String[] args)
{
new NetWin();
}
}
class NetWin extends Frame implements ActionListener, Runnable
{
Button btn;
URL url;
TextField text;
TextArea area;
byte b[] = new byte[118];
Thread thread;
public NetWin()
{
text = new TextField(20);
area = new TextArea(12, 12);
btn = new Button("OK");
btn.addActionListener(this);
thread = new Thread(this);
Panel panel = new Panel();
panel.add(new Label("Address:"));
panel.add(text);
panel.add(btn);
add(area, BorderLayout.CENTER);
add(panel, BorderLayout.NORTH);
setBounds(60, 60, 360, 360);
setVisible(true);
validate();
addWindowListener(new WindowAdapter()
{public void windClosing(WindowEvent e){
System.exit(0);
}});
}
public void actionPerformed(ActionEvent e)
{
if(!(thread.isAlive()))
thread = new Thread(this);
try{
thread.start();
}
catch(Exception e1){
text.setText("I’m reading "+url);
}
}
public void run()
{
try{
int n = -1;
area.setText(null);
String name = text.getText().trim();
/*Create an URL object*/
/*Retrieve the information of this URL and displays in the TextArea: host:xxx port:xxx filename:xxx */
/*Read the web page, retrieve the URLs of all the pictures in this page, and display them in the TextArea.*/
}
catch(MalformedURLException e1)
{
text.setText("" + e1);
return;
}
catch(IOException e2)
{
text.setText("" + e2);
return;
}
}
}
Code:
package exp5;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class exp5_1
{
public static void main(String[] args)
{
new NetWin();
}
}
class NetWin extends Frame implements ActionListener, Runnable
{
Button btn;
URL url;
TextField text;
TextArea area;
byte b[] = new byte[118];
Thread thread;
public NetWin()
{
text = new TextField(20);
area = new TextArea(12, 12);
btn = new Button("OK");
btn.addActionListener(this);
thread = new Thread(this);
Panel panel = new Panel();
panel.add(new Label("Address:"));
panel.add(text);
panel.add(btn);
add(area, BorderLayout.CENTER);
add(panel, BorderLayout.NORTH);
setBounds(60, 60, 360, 360);
setVisible(true);
validate();
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}
);
}
public void actionPerformed(ActionEvent e)
{
if(!(thread.isAlive()))
thread = new Thread(this);
try
{
thread.start();
}
catch(Exception e1)
{
text.setText("I’m reading "+url);
}
}
public void run()
{
try
{
int n = -1;
String name = text.getText().trim();
url=new URL(name);
area.setText("Host:"+url.getHost()+"\nPort:"+url.getPort()+"\nFilename:"+url.getFile());
Scanner sc=new Scanner(url.openConnection().getInputStream());
String line;
while( (line=sc.nextLine())!=null)
{
int i=line.indexOf("src='/UploadFile/");
String sub;
if(i>=0)
{
int i2=line.indexOf("'",i+5);
sub=line.substring(i+5,i2);
area.append("\n"+sub);
area.append("\n");
}
}
/*Create an URL object*/
/*Retrieve the information of this URL and displays in the TextArea: host:xxx port:xxx filename:xxx */
/*Read the web page, retrieve the URLs of all the pictures in this page, and display them in the TextArea.*/
}
catch(MalformedURLException e1)
{
text.setText("" + e1);
return;
}
catch(IOException e2)
{
text.setText("" + e2);
return;
}
}
}
Result:
2) Transfer some objects with stream sockets.
Create a server application and a client application using stream sockets.
The client connects to the server and transfers an object of class Course.
The server receives the object and prints a) connected successfully; 2) information of this Course object; 3) the IP address and port of the client.
Class Course looks as follows:
class Course implements Serializable {
private String name;
private int score;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
}
Code:
package exp5;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.net.Socket;
class Course implements Serializable {
private String name;
private int score;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public int getScore()
{
return score;
}
public void setScore(int score)
{
this.score = score;
}
}
public class exp5_2 {
public static void main(String[] args) throws Exception
{
Socket socket=new Socket("localhost",12345);
Course course1=new Course();
course1.setName("hahaha");
course1.setScore(60);
ObjectOutputStream os= new ObjectOutputStream(socket.getOutputStream());
os.writeObject(course1);
socket.getOutputStream().flush();
socket.close();
}
}
package exp5;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerTest {
public static void main(String[] args) throws Exception
{
ServerSocket sc=new ServerSocket(12345);
Socket socket=sc.accept();
ObjectInputStream ois= new ObjectInputStream(socket.getInputStream());
Course course1= (Course) ois.readObject();
System.out.println("Name : "+ course1.getName());
System.out.println("Score: "+ course1.getScore());
socket.close();
}
}
3) Transfer an image using Datagram sockets.
1) The code of a client application is provided as follows:
import java.io.*;
import java.net.*;
import java.awt.event.*;
import java.awt.*;
public class ImageClient extends Frame implements ActionListener, Runnable
{
Button btn = new Button("Acquire an image");
ImageCanvas ic;
public ImageClient()
{
super("Client");
setSize(320, 200);
setVisible(true);
btn.addActionListener(this);
add(btn, BorderLayout.NORTH);
ic = new ImageCanvas();
add(ic, BorderLayout.CENTER);
Thread thread = new Thread(this);
validate();
addWindowListener(new WindowAdapter(){
@Override
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
thread.start();
}
public void actionPerformed(ActionEvent event)
{
byte b[] = "Please send me an image.".trim().getBytes();
try{
InetAddress addr = InetAddress.getByName("127.0.0.1");
DatagramPacket data = new DatagramPacket(b, b.length, addr, 1234);
DatagramSocket mailSend = new DatagramSocket();
mailSend.send(data);
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void run()
{
DatagramPacket pack = null;
DatagramSocket mailReceive = null;
byte b[] = new byte[8192];
ByteArrayOutputStream out = new ByteArrayOutputStream();
try{
pack = new DatagramPacket(b, b.length);
mailReceive = new DatagramSocket(5678);
}
catch(Exception e){
e.printStackTrace();
}
try{
while(true)
{
mailReceive.receive(pack);
String message = new String (pack.getData(), 0, pack.getLength());
if(message.startsWith("end"))
break;
out.write(pack.getData(), 0, pack.getLength());
}
byte imagebyte[] = out.toByteArray();
out.close();
Toolkit tool = getToolkit();
Image image = tool.createImage(imagebyte);
ic.setImage(image);
ic.repaint();
validate();
}
catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args)
{
new ImageClient();
}
}
class ImageCanvas extends Canvas
{
Image im = null;
public ImageCanvas()
{
setSize(200, 200);
}
public void paint(Graphics g)
{
if(im != null)
g.drawImage(im, 0, 0, this);
}
public void setImage(Image im)
{
this.im = im;
}
}
2) The code of a server application is provided as follows:
import java.io.*;
import java.net.*;
public class ImageServer {
public static void main(String[] args)
{
DatagramPacket pack = null;
DatagramSocket mailReceive = null;
ImageServerThread thread;
byte b[] = new byte[8192];
InetAddress address = null;
pack = new DatagramPacket(b, b.length);
while(true)
{
/*Create the object mailReceive to listen to the request. */
/*Acquire the request infomation from a client. Retrieve the address of the client. */
if(address != null)
{
new ImageServerThread(address).start();
}
else
continue;
}
}
}
class ImageServerThread extends Thread
{
InetAddress address;
DataOutputStream out = null;
DataInputStream in = null;
String s = null;
ImageServerThread(InetAddress address)
{
this.address = address;
}
public void run()
{
FileInputStream in;
byte b[] = new byte[8192];
try{
in = new FileInputStream("D:/a.jpg");
int n = -1;
while((n = in.read(b)) != -1)
{
/*Read the image data and sent them to the client.*/
}
in.close();
byte end[] = "end".getBytes();
/*Send the message of “end” to the client. */
}
catch(Exception e) {
e.printStackTrace();
}
}
}
Code:
package exp5;
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Canvas;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.ByteArrayOutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class ImageClient extends Frame implements ActionListener, Runnable
{
Button btn = new Button("Acquire an image");
ImageCanvas ic;
public ImageClient()
{
super("Client");
setSize(320, 200);
setVisible(true);
btn.addActionListener(this);
add(btn, BorderLayout.NORTH);
ic = new ImageCanvas();
add(ic, BorderLayout.CENTER);
Thread thread = new Thread(this);
validate();
addWindowListener(new WindowAdapter()
{
@Override
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
thread.start();
}
public void actionPerformed(ActionEvent event)
{
byte b[] = "Please send me an image.".trim().getBytes();
try
{
InetAddress addr = InetAddress.getByName("127.0.0.1");
DatagramPacket data = new DatagramPacket(b, b.length, addr, 1234);
DatagramSocket mailSend = new DatagramSocket();
mailSend.send(data);
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void run()
{
DatagramPacket pack = null;
DatagramSocket mailReceive = null;
byte b[] = new byte[8192];
ByteArrayOutputStream out = new ByteArrayOutputStream();
try
{
pack = new DatagramPacket(b, b.length);
mailReceive = new DatagramSocket(5678);
}
catch(Exception e)
{
e.printStackTrace();
}
try
{
while(true)
{
mailReceive.receive(pack);
String message = new String (pack.getData(), 0, pack.getLength());
if(message.startsWith("end"))
break;
out.write(pack.getData(), 0, pack.getLength());
}
byte imagebyte[] = out.toByteArray();
out.close();
Toolkit tool = getToolkit();
Image image = tool.createImage(imagebyte);
ic.setImage(image);
ic.repaint();
validate();
}
catch(Exception e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
new ImageClient();
}
}
class ImageCanvas extends Canvas
{
Image im = null;
public ImageCanvas()
{
setSize(200, 200);
}
public void paint(Graphics g)
{
if(im != null)
g.drawImage(im, 0, 0, this);
}
public void setImage(Image im)
{
this.im = im;
}
}
package exp5;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class ImageServer
{
public static void main(String[] args)
{
DatagramPacket pack = null;
DatagramSocket mailReceive = null;
ImageServerThread thread;
byte b[] = new byte[8192];
InetAddress address = null;
pack = new DatagramPacket(b, b.length);
while(true)
{
try
{
mailReceive =new DatagramSocket(1234);
}
catch(IOException e)
{
System.out.println("######");
}
/*Create the object mailReceive to listen to the request. */
try
{
mailReceive.receive(pack);
address=pack.getAddress();
System.out.println("######"+address);
}
catch(IOException e)
{
e.printStackTrace();
}
if(address != null)
{
new ImageServerThread(address).start();
}
else
continue;
}
}
}
class ImageServerThread extends Thread
{
InetAddress address;
DataOutputStream out = null;
DataInputStream in = null;
String s = null;
ImageServerThread(InetAddress address)
{
this.address = address;
}
public void run()
{
FileInputStream in;
byte b[] = new byte[8192];
try
{
in = new FileInputStream("C:/Users/Administrator/Desktop/haha.jpg");
int n = -1;
while((n = in.read(b)) != -1)
{
DatagramPacket data=new DatagramPacket(b,0,n,address,5678);
DatagramSocket mailSend=new DatagramSocket();
mailSend.send(data);
/*Read the image data and sent them to the client.*/
}
in.close();
byte end[] = "end".getBytes();
DatagramPacket data = new DatagramPacket(end,0, end.length , address,5678);
DatagramSocket mailSend=new DatagramSocket();
mailSend.send(data);
/*Send the message of “end” to the client. */
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
4、(Multithreaded Server) Multithreaded servers are quite popular today, especially because of the increasing use of multicore servers. Modify the simple server application presented to be a multithreaded server. Then use several client applications and have each of them connect to the server simultaneously. Use an ArrayList to store the client threads. ArrayList provides several methods to use in this exercise. Method size determines the number of elements in an ArrayList. Method get returns the element in the location specified by its argument. Method add places its argument at the end of the ArrayList. Method remove deletes its argument from the ArrayList.
```````