Download Section 9 Network Programming

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Programming Section 9
Lab Exercises September 2003
By James King
Contents
Contents ......................................................................................................................... 2
Table of Figures ............................................................................................................. 2
Section 9 Network Programming................................................................................... 3
Stand alone Version ................................................................................................... 5
Networked Version .................................................................................................... 6
Networking Using TCP.............................................................................................. 7
Networking Using UDP ........................................................................................... 10
Table of Figures
Figure 9-1: Using ping to identify your machines name ............................................... 6
2
Section 9 Network Programming
Most local area networks and the entire Internet use the TCP/IP protocol for
communication between machines. TCP sits on top of IP and provides reliability,
sequencing and the ability to split large messages into multiple IP packets. IP provides
a unique address for every machine connected to the network or Internet
independently of the hardware technology used to network the machine. The IP
address is 4 bytes long and usually written with a dot between each number for
instance 192.12.21.7
Communication usually requires addresses or names so that you can label your data
for a certain named recipient. Paper mail works this way the address includes the
name of a person to receive the letter and the location to send the data to. Addressing
on the Internet is also in two parts, in this case the address of the machine to
communicate with and a port number. A single application can be connected to a port
on any one machine and therefore, indirectly, the port number identifies the
application to talk to.
You don’t actually have to be part of a network to write network programs. Inside
every computer configured with IP is the ability to talk to yourself! We will use this
ability to run two entirely separate Java programs on the same machine and get them
to talk together using Java’s networking capability. The only change required to make
them work on two networked machines is to change the addresses the programs
connect to.
In this case we will connect our server to port 6666 and we can talk to ourselves via
the IP address 127.0.0.1 or the name localhost (which is translated into 127.0.0.1).
The Internet protocols have two different systems for delivering data TCP and UDP.
UDP has more limitations but has the potential to be faster. In Java programming for
TCP is much easier than UDP but this is because UDP in Java is not well thought-out
and not because programming UDP in every language is more complex.
ServerSocket sv=new ServerSocket(6666,1);
This creates port 6666 on the machine the program is executing on. ServerSocket
means that it is going to use TCP to communicate.
Socket s=sv.accept();
Accept makes the program sleep until a client tries to connect to that port. When the
client connects the program will wake up and s will be a temporary socket for the
server to talk to the newly connected client.
In Java a socket has built into it a Input Stream and a Output Stream. Around these we
can connect other streams to send structured data similar to the File and Stream labs.
InputStream i=s.getInputStream();
DataInputStream oi=new DataInputStream(i);
3
String h=oi.readUTF();
We can then read from the DataInputStream Ignoring the fact that it is connected to a
network socket rather than a file.
Like file input output the streams should be closed when no longer needed and any
stream operation can cause an exception if it did not work.
import java.io.*;
import java.net.*;
public class server
{
public server()
{
}
public void doit()
{
try
{
ServerSocket sv=new ServerSocket(6666,1);
System.out.println("waitng for client");
Socket s=sv.accept();
System.out.println("got a client");
InputStream i=s.getInputStream();
DataInputStream oi=new DataInputStream(i);
String h=oi.readUTF();
System.out.println(h);
oi.close();
i.close();
}
catch (Exception e)
{
System.err.println(e);
e.printStackTrace();
}
}
}
The client is similar to the server it creates a socket and connects the socket to port
666 on the same machine it is run on
Socket sv=new Socket("localhost",6666);
Around the socket it connects a DataOutputStream and just like file handling when
data is written to the stream you need to flush the stream to get data out from the
buffer.
4
import java.net.*;
import java.io.*;
public class client
{
public client()
{
}
public void doit()
{
try
{
System.out.println("trying to connect");
Socket sv=new Socket("localhost",6666);
OutputStream i=sv.getOutputStream();
DataOutputStream oi=new DataOutputStream(i);
oi.writeUTF("Hello World");
i.flush();
oi.flush();
oi.close();
i.close();
}
catch (Exception e)
{
System.err.println(e);
e.printStackTrace();
}
}
}
Stand alone Version
If you have no network you can run TWO copies of BlueJ. Type one class into
one copy of BlueJ and save it somewhere and type the other class into the other
BlueJ and save it somewhere else. This is because if you have two copies of BlueJ
both editing code in the same place you can get inconsistencies because changes
made in one copy will not be picked up by the other. Running two copies of
BlueJ will require quite a lot of memory...
Run the doit method of the server first. You should see a window appear saying
waiting for client. Now you can run the client. The server should display the message
sent by the client.
5
Networked Version
Create both classes using BlueJ but save them into the same directory. Find a partner
machine. Decide between you who will run the client and who will run the server. We
need to find the network name of the machine that will be the server so that the client
can connect to it. You can do this by running a command or Msdos window and then
typing in
ping localhost
This will respond with information about the local network configuration. See Figure
9-1.
Figure 9-1: Using ping to identify your machines name
In this case you can see the machines name is 8382.hope.ac.uk. Now we have the
machine name in the client replace the word localhost with the name of machine
being careful to make sure the “” are still there. In my case this would be
Socket sv=new Socket("8382.hope.ac.uk",6666);
Run the server on the machine you ran ping on and the client on another machine and
watch the magic. Congratulations you have just sent data through the network!
6
Networking Using TCP
TCP allows you to connect most of the same streams to it that you can to a file. You
can use DataInput and DataOutput Streams, you can send objects through the network
by using ObjectInput and ObjectOutput streams and you can communicate in ASCII
using bufferedReader and bufferedWriter.
Take the client and server example above and modify it to use bufferedReader and
bufferedWriter. (You can use the File handling examples to help you determine what
to change) Hint: Sockets only provide methods to get the Input and Output Streams.
However, BufferedReader and BufferedWritter require Reader and Writters to
connect to and so you cannot connect a BufferedReader and BufferedWritter directly
to a socket. Fortunately you can wrap the sockets input and output Streams in a
InputStreamReader and OutputStreamWriter which convert the input and output
streams into reader and writers. Yuch!
Take the client and server example above and modify it to use ObjectInput and
ObjectOutput. (again refer to the File handling examples.
7
Modification to the servers’ doit to send and receive ASCII
ServerSocket sv=new ServerSocket(6666,2);
System.out.println("waitng for client");
Socket s=sv.accept();
InputStream i=s.getInputStream();
InputStreamReader ir=new InputStreamReader(i);
BufferedReader oi=new BufferedReader(ir);
String h=oi.readLine();
System.out.println(h);
Modification to the clients’ doit to send and receive ASCII
System.out.println("trying to connect");
Socket s=new Socket("localhost",6666);
OutputStream i=s.getOutputStream();
OutputStreamWriter ir=new OutputStreamWriter(i);
BufferedWriter oi=new BufferedWriter(ir);
oi.write("Hello World");
oi.newLine();
Modifications for Serialization
New class called Hello
import java.io.*;
public class Hello implements Serializable
{
private String hello="";
public Hello(String h)
{
hello=h;
}
public Hello()
{
hello="";
}
public String message()
{
// put your code here
return hello;
}
}
8
Modifications for Serialization changes to the servers’ doit method
ServerSocket sv=new ServerSocket(6666,2);
System.out.println("waitng for client");
Socket s=sv.accept();
InputStream i=s.getInputStream();
ObjectInputStream oi=new ObjectInputStream(i);
Hello h=(Hello)oi.readObject();
System.out.println(h.message());
Modifications for Serialization changes to the clients’ doit method
System.out.println("trying to connect");
Socket sv=new Socket("localhost",6666);
OutputStream i=sv.getOutputStream();
ObjectOutputStream oi=new ObjectOutputStream(i);
Hello h=new Hello("Hello World");
oi.writeObject(h);
i.flush();
9
Networking Using UDP
In Java UDP networking is completely different from TCP, there are no readers or
writers, no streams. With Java UDP you can only send a lump (array) of bytes. That’s
right no OOP no objects no lovely abstractions back to basics.
The paradigm is also different. The server does not create a main socket and then wait
for a client to connect and then communicate using a temporary socket. With UDP
there is no connect there is no temporary socket all the communications go direct to
the main socket the server sets up. Try this
import java.net.*;
import java.io.*;
public class client
{
public client()
{
}
private void doit()
{
try
{
System.out.println("trying to send");
byte [] bytes="Hello World".getBytes();
DatagramSocket sv=new DatagramSocket();
DatagramPacket p=new
DatagramPacket(bytes,bytes.length,InetAddress.getByName("localhost")
,6666);
sv.send(p);
sv.close();
}
catch (Exception e)
{
System.err.println(e);
e.printStackTrace();
}
}
public static void main(String args[])
{
client s = new client();
s.doit();
}
}
10
import java.io.*;
import java.net.*;
public class server
{
public server()
{
}
private void doit()
{
try
{
byte [] bytes=new byte[65536];
DatagramSocket sv=new DatagramSocket(6666);
DatagramPacket p=new DatagramPacket(bytes,bytes.length);
sv.receive(p);
bytes=p.getData();
sv.close();
String h=new String(bytes,0,p.getLength());
System.out.println(h);
}
catch (Exception e)
{
System.err.println(e);
e.printStackTrace();
}
}
public static void main(String args[])
{
server s = new server();
s.doit();
}
}
11