Upload
nguyen-dac-trung
View
230
Download
0
Embed Size (px)
Citation preview
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 1/78
1
Session 4. Network programming
with socket and datagram Socket
InetAddress
TCP socket
UDP socket (Datagram)
Case study 3
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 2/78
2
What is a socket? Original idea came from UNIX
“The network is just like a file system”
Read and write a stream of data “to thenetwork” through socket
A socket is bound to a port number so that
the TCP layer can identify the correct
application for the data
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 3/78
3
Introduction to Sockets Why Sockets?
Used for Interprocess communication.
The Client-Server model
Most interprocess communication uses client-server
model
Client & Server are two processes that wants to
communicate with each other The Client process connects to the Server process, to
make a request for information/services own by the
Server.
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 4/78
4
Once the connection is established between
Client process and Server process, they can start
sending / receiving information.
What are Sockets?
End-point of interprocess communication.
An interface through which processes can send /
receive information
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 5/78
5
Port
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 6/78
6
Communication between
processes : using port and socket
message
agreed port any port
socket socket
Internet address = 138.37.88.249 Internet address = 138.37.94.248
other ports client server
• Port: The destination of a message• Socket: The final point for processes communication• Each socket is associated with UDP or TCP
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 7/78
7
Port
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 8/78
8
Local socket address: Local IP address and port
number Computer’s address likes IP address, example:
203.162.36.149 mapping with www.cit.ctu.edu.vn
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 9/78
9
The InetAddress class The java.net.InetAddress class is used to
represent an IP address as an object. It is
also used to resolve from host name to IPaddress and vice versa.
No Constructors, instead, factory methods
are provided.
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 10/78
10
Static InetAddress
getByName(String host)
Takes a hostname and returnsInetAddress object representing
its IP address. Static InetAddress[]
getAllByName(String
host)
Takes a hostname and returnsan array of InetAddress objectsrepresenting its IP addresses.
static InetAddress
getLocalHost()
Returns an InetAddress objectrepresenting the IP address of the local host
String getHostAddress() Returns IP address string of thisInetAddress object
string getHostName() Returns the hostname of thisInetAddress object.
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 11/78
11
public class IPAddress {
public static void main(String[] agrs){try {
InetAddress local = InetAddress.getLocalHost();
InetAddress[] addresses =
InetAddress.getAllByName(local.getHostName());System.out.println("My Address is: "+local);
System.out.println("My Host name is: "+local.getHostName());
System.out.println("My IP Address is: "+local.getHostAddress());
for(int i=0;i<addresses.length;i++){System.out.println(addresses[i]);
} } catch (UnknownHostException ex) {
System.out.println("Exception :"+ex);
} }}
IPAddress.java
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 12/78
12
TCP Sockets (Stream Sockets) Java provides two classes for creating TCP
sockets: Socket and ServerSocket.
The ServerSocket class is used to by serverto accept client connections.The
constructors for the class are:
public ServerSocket(int port) public ServerSocket(int port, int backlog)
public ServerSocket(int port, int backlog,
InetAddress networkInterface)
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 13/78
13
This class is used by clients to make a
connection with a server
Socket constructors are: Socket(String hostname, int port)
Socket(InetAddress addr, int port)
Socket(String hostname, int port, InetAddress localAddr, int localPort)
Socket(InetAddress addr, int port, InetAddress
localAddr, int localPort)
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 14/78
14
Algorithm for TCP server Find the IP address and port number of server
Create a TCP server socket
Bind the server socket to server IP and Port number
(this is the port to which clients will connect)
Accept a new connection from client
returns a client socket that represents the client
which is connected Send/ receive data with client using the client socket
Close the connection with client
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 15/78
15
Algorithm for TCP client Find the IP address and port number of server
Create a TCP socket
Connect the socket to server (Server must be
up and listening for new requests)
Send/ receive data with server using the
socket
Close the connection
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 16/78
16
The socket APIs for connection-oriented protocol (TCP)
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 17/78
17
Reading from/ Writing to a
Socket
var1
var2
Socket
InputStream
OutputStream
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 18/78
18
On the TCP server side ServerSocket objects use their accept() method to
connect to a client
public Socket accept()
accept() method returns a Socket object, and its
getInputStream() and getOutputStream()
methods provide streams for reading and writing
to the client. There are no getInputStream() or
getOutputStream() methods for ServerSocket
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 19/78
19
Reader/Writer
BufferedReader reader=null;
PrintWriter writer=null;
reader=new BufferedReader(new
InputStreamReader(client.getInputStream()));
writer.println("Welcome to my server!!");
writer=new PrintWriter(client.getOutputStream(), true);
String msg=reader.readLine();
DataInputStream reader=null;
DataOutputStream writer=null;
reader = new DataInputStream(client.getInputStream());
writer=new DataOutputStream(client.getOutputStream());
writer.writeUTF(msg);
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 20/78
20
Close:
writer.close();
reader.close();
client.close();
server.close();
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 21/78
21
public class TcpEchoServer {
public static void main(String[] agrs) throws IOException{
ServerSocket server=null;
Socket client=null;
BufferedReader reader=null;
PrintWriter writer=null;
int port=1234;
try {
server = new ServerSocket(port);
System.out.println("Waiting connection...");
client=server.accept();
} catch (IOException ex) {
System.err.println("Could not listen on port "+port);
System.exit(1);
}
TcpEchoServer.java
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 22/78
22
reader=new BufferedReader(new
InputStreamReader(client.getInputStream()));
writer=new PrintWriter(client.getOutputStream(), true);
writer.println("Welcome to my server!!");
String msg;
while((msg = reader.readLine())!= null){
System.out.println("Message from client: "+msg);writer.println(msg);
if(msg.equals("Bye!"))
break;
}writer.close(); reader.close();
client.close(); server.close();
}}
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 23/78
23
On the TCP client side Data is sent and received with output and input
streams.
The Socket class has the following methods, that
retruns InputStream and the OutputStream for
reading and writing to the socket
public InputStream getInputStream()
public OutputStream getOutputStream() There's also a method to close a socket:
public synchronized void close()
T E h Cli t j
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 24/78
24
public class TcpEchoClient {
public static void main(String[] agrs) throws IOException{
Socket client=null;BufferedReader reader=null;
PrintWriter writer=null;
BufferedReader in=null; int port=1234;
try {client = new Socket("localhost", port);
reader=new BufferedReader(new
InputStreamReader(client.getInputStream()));
writer=new PrintWriter(client.getOutputStream(), true);} catch (UnknownHostException ex) {
System.err.print(ex); System.exit(1);
} catch (IOException ex) {
System.err.println(ex); System.exit(1); }
TcpEchoClient.java
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 25/78
25
in=new BufferedReader(new InputStreamReader(System.in));
System.out.println(reader.readLine());
String msg;
System.out.print("Enter message :");while((msg=in.readLine()).length()!=0){
writer.println(msg);
System.out.println("message from server:"+reader.readLine());
System.out.print("Enter message :");}
in.close();
writer.close();
reader.close();
client.close();
}
}
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 26/78
26
TCP chatting
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 27/78
27
chatServer.javaServerSocket server=null;
Socket client=null;
BufferedReader reader=null;
PrintWriter writer=null;
String msg;
private void btSendActionPerformed(java.awt.event.ActionEventevt) {
String s=message.getText();
room.append("Server: "+s+"\n");
writer.println(s);message.setText("");
}
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 28/78
28
public void listenSocket() {
try {
server = new ServerSocket(1234);
} catch (IOException ex) {
System.out.println("Could not listen on port 1234");
System.exit(1);
}try{
client = server.accept();
} catch (IOException ex) {
System.out.println("Accept failed : 1234");
System.exit(1);
}
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 29/78
29
try{
reader=new BufferedReader(new
InputStreamReader(client.getInputStream()));
writer=new PrintWriter(client.getOutputStream(),true);}catch(IOException e){
System.out.print("Accept failed: 1234");
System.exit(1);}
while(true){try{
msg = reader.readLine();
room.append("client:"+msg+"\n");
} catch (IOException ex) {System.out.println("Read fialed");
System.exit(1);
}}}
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 30/78
30
protected void finalize(){
//Clean up
try{
reader.close();
writer.close();
server.close();
} catch (IOException e) {
System.out.println("Could not close.");
System.exit(1);
}
}
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 31/78
31
chatClient.javaSocket client=null;
BufferedReader reader=null;PrintWriter writer=null;
String msg;
private void
btSendActionPerformed(java.awt.event.ActionEvent evt) {
String s=message.getText();
room.append("client: "+s+"\n");
writer.println(s);message.setText("");
}
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 32/78
32
public void listenSocket(){
try {
client = new Socket("localhost", 1234);
} catch (UnknownHostException ex) {System.out.print("Accept failed: 1234");
System.exit(1);
} catch (IOException ex) {
System.out.print("Accept failed: 1234");
System.exit(1);
}
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 33/78
33
try{
reader=new BufferedReader(new
InputStreamReader(client.getInputStream()));
writer=new PrintWriter(client.getOutputStream(),true);
}catch(IOException e){
System.out.print("Accept failed: 1234");
System.exit(1); }
while(true){
try{
msg = reader.readLine();
room.append("server:"+msg+"\n");
} catch (IOException ex) {
System.out.println("Read fialed");
System.exit(1);
}}
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 34/78
34
protected void finalize(){
//Clean up
try{reader.close();
writer.close();
client.close();} catch (IOException e) {
System.out.println("Could not close.");
System.exit(1);}
}
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 35/78
35
What are Sockets and Threads? A server program typically provides
resources to a network of client
programs. Client programs send
requests to the server program, andthe server program responds to the
request.
One way to handle requests from more than one client is to
make the server program multi-threaded. A multi-threadedserver creates a thread for each communication it accepts
from a client. A thread is a sequence of instructions that run
independently of the program and of any other threads.
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 36/78
36
Creating Threads in Java Runnable interface
Create object implementing Runnable interface Pass it to Thread object via Thread constructor
Example
public class MyT implements Runnable {
public void run() {
… // work for thread
}
}
Thread t = new Thread(new MyT()); // create thread
t.start(); // begin running thread
… // thread executing in parallel
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 37/78
37
threadServer.javaclass Clients implements Runnable{
private Socket client;
private JTextArea text;Clients(Socket client, JTextArea text){
this.client=client;
this.text=text;
}
bli id () {
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 38/78
38
public void run() {
String message;
BufferedReader read = null;
PrintWriter write = null;
…………………
while(true){
try {
message = read.readLine();
String[] data;
data=message.split("-");
//Send data back to client
write.println("Server "+data[1]);
text.append(data[0]+" "+data[1]+"\n");
} catch (IOException ex) {
System.out.print("read failed");
System.exit(-1);
} }
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 39/78
39
public class threadServer extends javax.swing.JFrame {
ServerSocket server;
private void listenSocket(){
server = new ServerSocket(1234);
……………..
while(true){
Clients c;
………..
c = new Clients(server.accept(), text);
Thread t=new Thread(c);
t.start();
…………….
}
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 40/78
40
threadClient.javaSocket client;
BufferedReader read=null;
PrintWriter write=null;
static String name=null;
/** Creates new form threadClient */
public threadClient() {
initComponents();name=JOptionPane.showInputDialog("Enter your name:");
txt.requestFocus();
}
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 41/78
41
public void listenSocket(){
……………
client = new Socket("localhost", 1234);
read=new BufferedReader(new
InputStreamReader(client.getInputStream()));
write=new PrintWriter(client.getOutputStream(),true);
…………………….}
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 42/78
42
private void
jButton1ActionPerformed(java.awt.event.ActionEvent evt)
{
String s=txt.getText();write.println(name+"-"+s);
text.append(name +" "+s+"\n");
txt.setText("");
//Receive text from server
try {
String ss = read.readLine();
text.append(ss+"\n");
} catch (IOException ex) {
System.out.print("read error");
System.exit(-1);
}}
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 43/78
43
UDP Sockets (Datagram Sockets) Packet is a block of data with length that can vary between
successive packets, ranging from 7 to 65,542 bytes, including
the packet header. Packets may travel along different paths
depending on the state of the network.
A datagram is an independent, self-contained message sent
over the network whose arrival, arrival time, and content are
not guaranteed.
Each packet has a time-to-live (TTL) counter, which is
updated when it is routed along to the next point in the
network. When the timer expires, it will be discarded, and
the recipient will not be notified.
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 44/78
44
Java Support for UDP Java provides two classes for creating UDP
Sockets:
DatagramPacket class, used to represent
the data for sending and receiving.
DatagramSocket class for creating a
socket used to send and receive
DatagramPackets.
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 45/78
45
DatagramPacket Class
A DatagramPacket object represents adata packet intended for transmission usingUDP.
It contains addressing information such asan IP address and a port.
When a DatagramPacket is read from a
UDP socket, the IP address/port of thepacket represents the address/port of thesender.
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 46/78
46
When a DatagramPacket is used to send a
UDP packet, the IP address/port represents theaddress/port of the recipient.
DatagramPacket
IP address (java.net.InetAddr)
Port address (int)
Packet data (byte[])
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 47/78
47
Creating a DatagramPacket
Constructor to use for creating aDatagramPacket for receiving incoming
UDP packets:DatagramPacket(byte[] buffer, int
length)
Example:byte b[]=new byte[1024];
DatagramPacket packet;
packet = new DatagramPacket(b, b.length);
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 48/78
48
Constructor for sending :public DatagramPacket(byte[] data, int
length, InetAddress addr, int port)
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 49/78
49
String s=”This is an example of UDP Programming”;
byte[] b= s.getBytes();
try{
InetAddress name=InetAddress.getByName(“www.vnn.vn”);
int port =1234;
DatagramPacket dataSend=new
DatagramPacket(b,b.length,name,port); //sending a packet
}
catch(IOException e){
System.err.println(e);
}
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 50/78
50
DatagramPacket Methods
InetAddress getAddress()
byte[] getData()
int getLength() int getPort()
void setAddress(InetAddress addr)
void setData(byte[] buffer) void setLength(int length)
void setPort(int port)
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 51/78
51
Creating a DatagramSocket
Constructor to use for creating a clientDatagramSocket:
DatagramSocket() throwsjava.net.SocketException
Example:DatagramSocket socket;
try {socket = new DatagramSocket();
} catch (SocketException exception) {
…}
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 52/78
52
Constructor to use for creating a server
DatagramSocket:DatagramSocket(int port) throws
java.net.SocketException
Example:DatagramSocket socket;
try {
socket = new DatagramSocket(2000);
} catch (SocketException exception) {
…
}
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 53/78
53
DatagramSocket Methods void close()
void connect(InetAddress r_addr, int r_port)
void disconnect()
InetAddress getInetAddress()
int getPort()
InetAddress getLocalAddress()
int getLocalPort()
int getReceiveBufferSize() throws
java.net.SocketException
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 54/78
54
int getSendBufferSize() throws java.net.SocketException
int getSoTimeout() throws
java.net.SocketException void receive(DatagramPacket packet) throws
java.io.IOException
void send(DatagramPacket packet) throws
java.io.IOException
int setReceiveBufferSize(int length) throws
java.net.SocketException
int setSendBufferSize(int length) throws java.net.SocketException
void setSoTimeout(int duration) throws
java.net.SocketException
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 55/78
55
UDP Server
Step 1:To open a server socket at port number
specified.
try {DatagramSocket myServer = new
DatagramSocket(port);
}
catch(SocketException e) {
System.out .println(e);
}
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 56/78
56
Step 2: Create a packet from the DatagramPacket object to
receive data from the client to process.
try { // reveive
byte[] receiveData = new byte[1024];
DatagramPacket receivePacket = new
DatagramPacket(receiveData, receiveData.length);
myServer.receive(receivePacket);
input = new String( receivePacket.getData());
// process data
}catch (SocketException e) {
System.out .println(e);}catch (IOException e) {
System.out .println(e);
}
Step 3:Packing DatagramPacket packet of information and to
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 57/78
57
Step 3: ac g atag a ac et pac et o o at o a d to
send it back to the client, respectively.
try { //Packing datagram
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
byte[] sendData = (dũ liệu đã xử lí).getBytes();
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress,
port);
// send it back to the client
myServer.send(sendPacket);
}catch (SocketException e) {
System.out .println(e);
}catch (IOException e) {
System.out .println(e);
}
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 58/78
58
UDP Client
Step 1: Open a socket client to server name
defined at a port number specified.
try {
mySocket = new DatagramSocket();
} catch (SocketException e) {
System.err .println(e);
}
Step 2: packaging information on DatagramPacket packet
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 59/78
59
Step 2: packaging information on DatagramPacket packet
to send.
byte[] sendData = new byte[1024]; // sending data buffer
try {netAddress IPAddress =
InetAddress.getByName("localhost");
sendData = (sending data).getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress,
port);
} catch (SocketException e) {
System.err .println(e);} catch (IOException e) {
System.err .println(e);
}
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 60/78
60
Step 3: Send data to the server.
try {
mySocket.send(sendPacket);} catch (SocketException e) {
System.err .println(e);
} catch (IOException e) {System.err .println(e);
}
Step 4: Wait to receive data (already processed)
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 61/78
61
Step 4: Wait to receive data (already processed).
byte[] receiveData = new byte[1024];
try {
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
mySocket.receive(receivePacket);
receivedData = receivePacket.getData();
} catch (SocketException e) {
System.err .println(e);
} catch (IOException e) {
System.err .println(e);}
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 62/78
62
Step 5: Close socket have been created.
try {
mySocket.close();
} catch (Exception e) {
System.err .println(e);
}
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 63/78
63
UDPServer.javapublic class UDPServer {
public static final int PORT = 1234;
public static final int BUFSIZE = 256;
DatagramSocket server = null; String input;
public void UDPServer(){
try {
server = new DatagramSocket(PORT);
} catch(SocketException e) {
System.out.println(e);
System.exit(1);
} }
public void listening(){
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 64/78
64
public void listening(){
byte[] receiveData = new byte[BUFSIZE];
byte[] sendData = new byte[BUFSIZE];
while(true){
try { // Receive data
DatagramPacket receivePacket = new
DatagramPacket(receiveData, receiveData.length);
try {
server.receive(receivePacket);
} catch (IOException ex) {
}input = new String( receivePacket.getData());
System.out.println(input);
InetAddress IPAddress = receivePacket getAddress();
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 65/78
65
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
sendData = input.getBytes();
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length,
IPAddress, PORT);
// Gui du lieu ve client
server.send(sendPacket);
}catch (SocketException e) {
System.out.println(e);
}catch (IOException e) {System.out.println(e);
} } }
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 66/78
66
UDPClient.javapublic class UDPClient {
public static final int PORT = 1234;
public static final int BUFSIZE = 256;
DatagramSocket client = null;
// Tao ket noi
public void connection(){
try {
client = new DatagramSocket();
} catch (SocketException e) {
System.err.println(e); System.exit(1);
}}
public void send(String str){
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 67/78
67
p ( g ){
if (client != null) {
byte[] sendData = new byte[BUFSIZE]; // bo dem gui du
lieutry {
InetAddress IPAddress=null;
try {
IPAddress = InetAddress.getByName("localhost");} catch (UnknownHostException ex) {
}
sendData = str.getBytes();
DatagramPacket sendPacket = newDatagramPacket(sendData, sendData.length, IPAddress, PORT);
client.send(sendPacket);
} catch (SocketException e) {
} catch (IOException e) { }}}
public String receive(){
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 68/78
68
public String receive(){
if (client != null) {
byte[] receiveData = new byte[BUFSIZE];
// bo dem nhan du lieutry {
DatagramPacket receivePacket = new
DatagramPacket(receiveData, receiveData.length);
client.receive(receivePacket);return new String(receivePacket.getData());
} catch (SocketException e) {
System.err.println(e);
} catch (IOException e) {System.err.println(e);
} }
return null; }
public static void main(String[] agrs){
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 69/78
69
p ( g[] g ){
UDPClient c=new UDPClient();
c.connection();
BufferedReader stdin=new BufferedReader(newInputStreamReader(System.in));
String msg=null;
while(true){
System.out.println("Input sessages: ");try {
msg = stdin.readLine();
} catch (IOException ex) { }
c.send(msg);System.out.println(c.receive());
if(msg.equals("exit"))
break; }
c.close(); }
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 70/78
70
Multicast in Java
There are following types of method for
delivering or transmitting data in the
network. Unicast
Multicast
Broadcast
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 71/78
71
Unicast
Unicast: This method solves network traffic
problems to deliver messages from one host
to another.
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 72/78
72
Multicast
Multicast: In this method, you can transmit
data or messages to all destination host
machines
Broadcast
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 73/78
73
Broadcast: It provides better facility to solve a network
traffic problems than unicast. In broadcast, the servergenerates only one data stream but it can be delivered to all
destination host whether interested or not. Here
transmitting data or packets to be received by every host
machine on entire network that means you send data or
messages to multiple host at a time or simultaneously
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 74/78
74
Multicast Server in Java when program runs that has two command buttons 'Start' and
'Stop'. First time 'Start' button is enable and another is disable.
When you click 'Start' button, the multicast server functions but
button is disable, and the message "Server is started" is
displayed in text area. If you want to stop the server then click on the 'Stop' button then multicast server resume its function
with a message that "Server is stopped". The multicast server
receives requests or messages from multicast client, which has
the port number '5000' and IP(Internate Protocol) number
('224.0.0.0', '235.0.0.1', '235.255.0.1', '224.0.255.1'). The server
also sends same message to all multicast clients that are
interested for this group otherwise don't perform these works.
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 75/78
75
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 76/78
76
UDP Multicast Client in Java That has four clients identified by the specific
IP('224.0.0.0', '235.0.0.1', '235.255.0.1', '224.0.255.1')
and port number(5000). Those of any client sends and
receives IP packet that depends upon the check box. If check box is enable then send or receive IP packets
otherwise it couldn't be send or receive. Just bellow
provides a text area that can be used for writing the
message and receiving the message to multicastserver. It has also 'Send' command button for sending
IP packet to multicast server.
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 77/78
77
8/3/2019 Session04-NP With Socket and Datagram
http://slidepdf.com/reader/full/session04-np-with-socket-and-datagram 78/78
Case study 3
5- 6 điểm: làm 2 bài ở mức 1
7- 8 điểm : qua mức 5-6 điểm, làm tiếp bài
ở mức 2
9- 10 điểm: qua mức 5-6 điểm, làm tiếp bàiở mức 3(chỉ cần chọn 1 trong 2 bài) – ưu
tiên bài 2 hơn.