Supp-Socket Programming

Transkript

Supp-Socket Programming
COM 362 Computer Networks I
1.
Principles of Networks Applications
2. TCP Socket Programming
Lec 2: Applicatin Layer:
3.
TCP/UDP Socket Programming
UDP Socket Programming
Prof. Dr. Halûk Gümüşkaya
[email protected]
[email protected]
http://www.gumuskaya.com
Computing Engineering Department
2
1
Sunday, February 24, 2013
Operations of a Socket
Abstract Stream Socket Service
A socket can perform 7 basic operations:
 Connect to a remote machine
(i.e. prepare to send or receive data)
 Send data
 Receive data
 Close a connection
 Asymmetric set-up, circuit abstraction

Java’s
Socket Class
(used by both
clients and servers)

 Bi-directional, continuous byte stream


 Bind to a port
 Listen for incoming data
 Accept connections from remote
machines on the bound port.
ServerSocket
Class
(needed only by
servers)
3
Server is passive, waits for connections
Client initiates the connections
TCP is free to break up and reorder the data however it
likes as long as the user sees an ordered byte stream
But often doesn’t
Stream jargon:
 A stream is a sequence of characters that flow into or out of a
process.
 An input stream is attached to some input source for the process, eg,
keyboard or socket.
 An output stream is attached to an output source, eg, monitor or
socket.
4
Java Socket Class (java.net package)
Socket Constructors
• The Socket class represents one end of a two-way
connection between your Java program and another program
on the network.
Commonly used constructors:
• It implements the client and data side of the two-way link.
public Socket(InetAddress host, int port) throws IOException
• If you are writing server software, the ServerSocket class
implements the server side of the two-way link.
Example:
public Socket(String host, int port) throws
UnknownHostException, IOException
try {
Socket fatih = new Socket(“fatih.edu.tr", 80);
}
catch (UnknownHostException e) {
System.err.println(e); }
} catch (IOException e) {
System.err.println(e); }
5
6
Stream Sockets in Java
Useful methods
 Socket and ServerSocket, classes
 inetAddress socket.getLocalAddress()



Both are TCP communication objects
Abstract asymmetry of client/server communication
Contain the stream objects once socket is connected

 socket.setSoTimeOut(int milliseconds)

 InPutStream, OutPutStream classes

get and receive bytes from a socket

block only for int milliseconds before returning
 socket.toString
 InetAddress class

get the machine’s local address

get the IP address and port number in a string
Object for containing an using IP addresses
Methods for viewing and changing IP addresses and
symbolic names
7
8
Reading From a Socket
Writing to a Socket
• To read from a Socket, after you create a socket to a given
address, you open an input stream on the socket.
• To write to a Socket, after you create a socket to a given
address, you open an output stream on the socket.
• The getInputStream() method returns an input stream that
can read data from the socket into a program.
• The getOutputStream( ) method returns a raw
OutputStream for writing data from your application to the
other end of the socket.
• You usually chain this InputStream to a filter stream or reader
that offers more functionality—DataInputStream or
InputStreamReader, for example—before reading input.
• It's also extremely helpful to buffer the input by chaining it to a
BufferedInputStream or a BufferedReader for
performance reasons.
• You usually chain this stream to a more convenient class like
DataOutputStream or OutputStreamWriter before using
it.
• For performance reasons, it's a good idea to buffer it as well.
9
Server Side Socket: ServerSocket
10
Constructors
• Java provides a ServerSocket class to allow programmers to
write servers.
• There are 4 public ServerSocket constructors:
public ServerSocket(int port) throws IOException
• Basically, a server socket's job is to sit by the phone and wait for
incoming calls.
public ServerSocket(int port, int backlog)
throws IOException
• More technically, a ServerSocket runs on the server and
listens for incoming TCP connections.
public ServerSocket(int port, int backlog, InetAddress
bindAddress) throws IOException
• Each ServerSocket listens on a particular port on the server
machine.
• When a client Socket on a remote host attempts to connect to
that port, the server wakes up, negotiates the connection
between the client and the server, and opens a regular Socket
between the two hosts.
• Server sockets wait for connections while client sockets
initiate connections.
11
public ServerSocket()
throws IOException
• These constructors let you specify the port, the length of the queue
used to hold incoming connection requests, and the local network
interface to bind to.
• They pretty much all do the same thing, though some use default
values for the queue length and the address to bind to.
12
Iterative Connection-Oriented TCP Server
Life Cycle of a Server
1. A new ServerSocket is created on a particular port using a
ServerSocket( ) constructor.
ServerSocket
Socket
DataOutputStream
DataInputStream
2. The ServerSocket listens for incoming connection attempts on
that port using its accept( ) method. accept( ) blocks until a
client attempts to make a connection, at which point accept( )
returns a Socket object connecting the client and the server.
server;
connection;
output;
input;
// bağlantı istekleri için
// sunucu veri haberleşme kanalı için
// I/O stream’ler
try {
// Adım 1: Bir ServerSocket’i oluştur.
server = new ServerSocket( 5000 );
3. Depending on the type of server, either the Socket's
getInputStream( ) method, getOutputStream( ) method, or
both are called to get input and output streams that communicate
with the client.
while ( true )
{
// Adım 2: Bir bağlantı için bekle.
connection = server.accept();
// Adım 3: Giriş/çıkış stream’leri hazırla.
input = new DataInputStream(connection.getInputStream());
output = new DataOutputStream(connection.getOutputStream());
// Adım 4: İşlem bağlantısı: sunucu-istemci iletişimi........
4. The server and the client interact according to an agreed-upon
protocol until it is time to close the connection.
// Adım 5: bağlantıyı kapa.
connection.close();
5. The server, the client, or both close the connection.
}
6. The server returns to step 2 and waits for the next connection.
// Adım 6: Adım 2’ye dön.
} catch ( IOException e ) {}
13
TCP Client
14
Iterative and Concurrent TCP Servers
Socket
client; // istemci veri haberleşme kanalı için
DataInputStream
input; // I/O stream’ler
DataOutputStream
output;
String hostname = “www.tcpserver.net"; // Sunucu makinenin DNS
adresi
try {
// Adım 1: Bağlantı yapmak için bir Socket oluştur.
client = new Socket(hostname, 5000);
// Adım 2: Giriş/çıkış stream’leri hazırla.
input = new DataInputStream( client.getInputStream() );
output = new DataOutputStream( client.getOutputStream() );
// Adım 3: İşlem bağlantısı.
// .... sunucu-istemci iletişimi........
// Adım 4: Bağlantıyı kapa..
client.close();
} catch ( IOException e ) {}
15
16
Example 2: Port Scanner
Port Scanner
Java Ağ Programcılığı, page: 368
import java.net.*;
import java.io.*;
>java PortScanner www.bilkent.edu.tr
01234567
Port 7 calismaktadir.
89
Port 9 calismaktadir.
10 11 12 13
Port 13 calismaktadir.
14 15 16 17 18 19
Port 19 calismaktadir.
20 21
Port 21 calismaktadir.
22 23
Port 23 calismaktadir.
24 25 26 27 28 29 30 31 32 33 34 35 36 37
Port 37 calismaktadir.
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
Port 79 calismaktadir.
80
Port 80 calismaktadir.
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
public class PortScanner {
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("kullanim: java PortScanner server");
System.exit(0);
}
InetAddress bilAdd = null;
try {
bilAdd = InetAddress.getByName(args[0]);
} catch (UnknownHostException e) {
System.err.println(e);
}
}
}
for (int i = 0; i < 100; i++) {
try {
System.out.print(i + " ");
InetSocketAddress socketaddress = new InetSocketAddress(bilAdd, i);
Socket s = new Socket();
s.connect(socketaddress, 500);
System.out.println("\nPort " + i + " calismaktadir.");
s.close();
} catch (IOException e) {
// Belirtilen portta hizmet bulunmamaktatir.
}
}
17
18
Example 3: Getting Connection Information
Port Scanner
Java Ağ Programcılığı, page: 371
import java.net.*;
import java.io.*;
>java PortScanner www.fatih.edu.tr
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
Port 21 calismaktadir.
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 7
5 76 77 78 79 80
Port 80 calismaktadir.
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
>java PortScanner www.microsoft.com
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 8
3 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
What’s wrong? If you increase timeout, we will also get response from the microsoft from some ports like 80.
• Your results will vary, depending on which ports are occupied.
• As a rule, more ports will be occupied on a Unix workstation than on a
PC or a Mac.
19
public class ConnInfo {
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("kullanim: java ConnInfo hostname");
System.exit(0);
}
InetAddress host = null;
try {
host = InetAddress.getByName(args[0]);
} catch (UnknownHostException e) {
System.err.println(e);
System.exit(0);
}
try {
Socket theSocket = new Socket(host, 80);
System.out.println("\ngetInetAddress() " + theSocket.getInetAddress());
System.out.println("getPort() " + theSocket.getPort());
System.out.println("getLocalAddress() " + theSocket.getLocalAddress());
System.out.println("getLocalPort() " + theSocket.getLocalPort());
System.out.println("getRemoteSocketAddress() " + theSocket.getRemoteSocketAddress());
System.out.println("getLocalSocketAddress() " + theSocket.getLocalSocketAddress());
theSocket.close();
}
catch (IOException e) {
System.err.println(e);
}
}
}
20
Two Different Runs
Example 4: Daytime Protocol Client
• One of the simplest protocols is called "daytime", and is defined in
RFC 867.
>java ConnInfo www.bilkent.edu.tr
getInetAddress() www.bilkent.edu.tr/139.179.10.16
getPort() 80
getLocalAddress() /139.179.198.17
getLocalPort() 1236
getRemoteSocketAddress() www.bilkent.edu.tr/139.179.10.16:80
getLocalSocketAddress() /139.179.198.17:1236
• The client opens a socket to port 13 on the daytime server.
• In response, the server sends the time in a human-readable format
and closes the connection.
>java ConnInfo www.fatih.edu.tr
• You can test the daytime server with Telnet like this:
getInetAddress() www.fatih.edu.tr/193.255.106.11
getPort() 80
getLocalAddress() /139.179.198.17
getLocalPort() 1237
getRemoteSocketAddress() www.fatih.edu.tr/193.255.106.11:80
getLocalSocketAddress() /139.179.198.17:1237
telnet www.time.gov 13
Conneting To www.time.gov
52541 02-09-24 07:10:57 50 0 0 147.7 UTC(NIST) *
• Let’s write Daytime Client in Java:
21
Daytime Protocol Client
22
Sockets and Ports in DaytimeClient
Java Ağ Programcılığı, page: 373
import java.net.*;
import java.io.*;
public class DayTimeClient {
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("kullanim: java DayTimeClient hostname");
System.exit(0);
}
InetAddress host = null;
try {
host = InetAddress.getByName(args[0]);
}
catch (UnknownHostException e) {
System.err.println(e);
System.exit(0);
}
try {
Socket theSocket = new Socket(host, 13);
InputStream is = theSocket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String data = br.readLine();
while (data != null) {
System.out.println(data);
data = br.readLine();
}
theSocket.close();
}
}
}
catch (IOException e) { System.err.println(e); }
>java DayTimeClient www.time.gov
52541 02-09-24 07:10:57 50 0 0 147.7 UTC(NIST) *
>java DayTimeClient www.bilkent.edu.tr
Tue Sep 24 10:09:00 2002
23
24
Iterative Connection-Oriented Server: DayTimeServer
Example 5: Java Ağ Programcılığı, page: 385
import java.net.*;
import java.io.*;
import java.util.Date;
>java DayTimeServer
Daytime Server is listening on port 13
New User from /139.179.11.24
New User from /127.0.0.1
public class DayTimeServer {
public static void main(String[] args) {
ServerSocket srvrSocket = null;
Socket connSocket;
OutputStream os;
try {
srvrSocket = new ServerSocket(13);
System.out.println("Daytime Server is listening on port 13");
}
catch (IOException e) {
System.err.println(e);
Syste.exit(0);
}
}
DayTimeServer and 2 Different Clients
Web Browser Client
while (true) {
try {
connSocket = srvrSocket.accept();
System.out.println("New User from " + connSocket.getInetAddress());
os = connSocket.getOutputStream();
Date now = new Date();
String currentDate = now.toString() + "\r\n";
os.write(currentDate.getBytes());
os.close();
connSocket.close();
}
catch (IOException e) { System.err.println(e); }
} // end of while
} // end of main
TELNET CLIENT:
tuna:/home1/csstu/oboyac$telnet 139.179.198.17 13
Trying 139.179.198.17...
Connected to 139.179.198.17.
Escape character is '^]'.
Wed Sep 26 00:30:54 EEST 2001
Connection closed by foreign host.
tuna:/home1/csstu/oboyac$
25
26
Example 6: A Simple Client/Server Application
Server
Java Ağ Programcılığı, page: 388
public class Server extends JFrame {
private JTextArea display;
private JScrollPane sp;
public Server() {
super("Server");
display = new JTextArea();
sp = new JScrollPane(display);
getContentPane().add(sp, BorderLayout.CENTER);
setSize(350, 250);
setVisible(true);
}
public static void main(String[] args) {
Server s = new Server();
s.setDefaultCloseOperation(EXIT_ON_CLOSE);
s.runServer();
}
public void runServer() {
ServerSocket server;
Socket connection;
DataOutputStream output;
DataInputStream input;
String line;
int counter = 1;
………..
27
28
Server (cont.)
Server (cont.)
try {
// Adim 1: Bir ServerSocket olustur.
server = new ServerSocket(6000, 100);
// Adim 5: Baglantiyi kapat.
display.append("\nTransmission complete. " + "Closing socket.\n\n");
connection.close();
++counter;
while (true) {
// Adim 2: Bir baglanti bekle........
display.append("Server is waiting for a client connection...\n");
connection = server.accept();
display.append("Connection " + counter + " received from: " +
connection.getInetAddress().getHostName());
// Adim 3: Giris ve cikis streamleri olustur
input = new DataInputStream(connection.getInputStream());
output = new DataOutputStream(connection.getOutputStream());
}
// Adim 6: 2. Adima geri don.
}
}
catch (IOException e) {
e.printStackTrace();
}
}
// Adim 4: Istemci sunucu islemleri
line = input.readUTF();
try {
if (line.compareTo("Selam") == 0) {
output.writeUTF("OK");
display.append("\nSending message \"Connection successful\"\n");
output.writeUTF("Connection successful");
display.append("Client message: " + input.readUTF());
}
else {
output.writeUTF("Sorry, your password is wrong...");
}
}
catch (IOException e) {
System.out.println(e);
}
………..
29
30
Client
Client (cont.)
public class Client extends JFrame {
private JTextArea display;
private JScrollPane sp;
try {
if (line.compareTo("OK") == 0) {
display.append("\nServer message: " + input.readUTF());
display.append("\nSending message \"Tesekkur ederim.\"\n");
output.writeUTF("Tesekkur ederim.");
}
else {
display.append("\nServer message: " + line);
}
}
catch (IOException e) {
System.out.println(e);
display.append("\nERROR\n"+e);
}
public Client() {
super("Client");
display = new JTextArea();
sp = new JScrollPane(display);
getContentPane().add(sp, BorderLayout.CENTER);
setSize(350, 250);
setVisible(true);
}
public void runClient() {
Socket client;
DataInputStream input;
DataOutputStream output;
String line;
// Adim 4: Baglantiyi kapat.
display.append("\nTransmission complete. " + "Closing connection.\n");
client.close();
try {
// Adim 1: Server'a bir Socket ile baglanmaya calis
client = new Socket(InetAddress.getLocalHost(), 6000);
display.append("Connected to: " + client.getInetAddress().getHostName());
}
// Adim 2: Baglanti yapildi, I/O stream'leri olustur.
input = new DataInputStream(client.getInputStream());
output = new DataOutputStream(client.getOutputStream());
}
catch (IOException e) {
e.printStackTrace();
display.append("\nERROR\n"+e);
}
public static void main(String[] args) {
Client c = new Client();
c.setDefaultCloseOperation(EXIT_ON_CLOSE);
c.runClient();
}
// Adim 3: Server ile etkilesim...
//output.writeUTF("Merhaba");
output.writeUTF("Selam");
line = input.readUTF();
……………….
}
31
32
A Chat Program: A Client/Server Application
More Examples: A Concurrent Client/Server Application
Java Ağ Programcılığı, page: 399
Java Ağ Programcılığı, page: 416
33
34
A Chat Program: A Client/Server Application
Java Ağ Programcılığı, page: 416
1.
Principles of Application Layer Protocols
2.
TCP Socket Programming
3. UDP Socket Programming
35
36
Abstract Datagram Socket Service
 No circuit abstraction, just send when ready
 Server is passive, waits for datagrams
 Client initiates the send
DatagramPacket Class
Constructors:
DatagramPacket(byte[] buf, int length)
DatagramPacket(byte[] buf, int offset, int length)
 Discrete packets (up to 64Kb long for UDP)
 UDP/IP maintains packet integrity
DatagramPacket(byte[] buf, int length, InetAddress address, int port)
DatagramPacket(byte[] buf, int offset, int length, InetAddress address, int port)
• All data in packet arrives or doesn’t (e.g. no half-packet)
– Even if lower layers fragment
• No data corruption (e.g. bit errors)
DatagramPacket(byte[] buf, int offset, int length, SocketAddress address)
DatagramPacket(byte[] buf, int length, SocketAddress address)
 Best effort
 Does not retransmit lost packets
 1 lost fragment -> whole packet is lost
The first two constructors are used when a DatagramPackect will be
received from the network.
The others are used when a DatagramPacket will be sent.
37
38
DatagramPacket Preparation
DatagramSocket Class
• To send or receive a DatagramPacket, you need to open a
datagram socket.
To create a DatagramPacket object to receive a data packet from net:
• In Java, a datagram socket is created and accessed through the
DatagramSocket class:
public class DatagramSocket extends Object
byte buffer = new byte[512];
DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
To send a DatagramPacket to the network:
Constructors:
try {
InetAddress addr = new InetAddess("www.doaminname.com");
int port = 3000;
String s = "UDP veri paketim: Selam sunucu"
byte[] b = s.getBytes();
DatagramPacket dp = new DatagramPacket(b, b.length, addr, port);
}
catch (UnknownHostException e) {
System.err.println(e);
}
public DatagramSocket() throws SocketException
public DatagramSocket(int port) throws SocketException
public DatagramSocket(int port, InetAddress laddr) throws SocketException
public DatagramSocket(SocketAddress bindaddr) throws SocketException
39
40
Sending a Datagram
Receiving a Datagram
try {
InetAddress addr = new InetAddess("wwww.server.com");
int port = 3000;
String s = "UDP veri paketim: Selam sunucu"
byte[] b = s.getBytes();
DatagramPacket dp = new DatagramPacket(b, b.length, addr, port);
}
catch (UnknownHostException e) {
System.err.println(e);
}
try {
byte buffer = new byte[65536];
DatagramPacket incoming = new DatagramPacket(buffer, buffer.length);
DatagramSocket ds = new DatagramSocket(2000);
ds.receive(dp); // wait for a UDP datagram
byte[] data = dp.getData();
String s = new String(data, 0, data.getLength());
System.out.println("Port " + dp.getPort() + " on " + dp.getAddress() + " sent this message:");
System.out.println(s);
}
catch (IOException e) {
System.err.println(e);
}
try {
DatagramSocket sender = new DatagramSocket();
sender.send(dp);
}
catch (IOException e) {
System.err.println(e);
}
41
42
Example 8: UDPCalc Client/Server Application
UDPCalcClient (1)
Java Ağ Programcılığı, page: 445
import java.io.*;
import java.net.*;
class UDPCalcClient {
public static void main(String args[]) throws Exception {
String host = "localhost";
if (args.length > 0) {
host = args[0];
}
System.out.print("Lutfen iki adet sayi giriniz:");
BufferedReader readNumbers = new BufferedReader(new InputStreamReader(System.in));
String sentence = readNumbers.readLine();
byte[] sendData = sentence.getBytes();
InetAddress IPAddress = InetAddress.getByName(host);
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 2468);
DatagramSocket calcClientSocket = new DatagramSocket();
calcClientSocket.setSoTimeout(5000);
int counter = 1;
byte[] receiveData = new byte[65508];
DatagramPacket resultPacket = new DatagramPacket(receiveData, receiveData.length);
43
44
UDPCalcClient (2)
UDPCalcServer
import java.io.*;
import java.net.*;
import java.util.StringTokenizer;
while (counter < 4) {
try {
calcClientSocket.send(sendPacket);
System.out.print("Paket " + counter + ".kez Gonderildi.”);
System.out.println(“Cevap Bekleniyor...");
calcClientSocket.receive(resultPacket);
String result = new String(resultPacket.getData(), 0, resultPacket.getLength());
System.out.print("Paket alindi. Cevap: " + result); break;
} catch (Exception e) {
counter++;
continue;
}
} // while son
class UDPCalcServer {
public static void main(String args[]) throws Exception {
DatagramSocket calcServerSocket = new DatagramSocket(2468);
byte[] receiveData = new byte[65508];
byte[] sendData = new byte[1024];
while (true) {
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
calcServerSocket.receive(receivePacket);
System.out.print("Packet received from " + receivePacket.getAddress());
System.out.print(" port " + receivePacket.getPort());
String sentence = new String(receivePacket.getData(), 0, receivePacket.getLength());
System.out.println(" Message:" + sentence);
String newSentence;
if (counter == 4)
System.out.println("Cevap alinamadi.");
} //main() son
} // sınıf son
}
}
}
try {
StringTokenizer st = new StringTokenizer(sentence, " x*");
int d1 = Integer.parseInt(st.nextToken());
int d2 = Integer.parseInt(st.nextToken());
newSentence = d1 + "*" + d2 + "=" + (d1 * d2) + "\n";
} catch (Exception e) {
newSentence = "Lutfen bosluk ile ayrilmis iki sayi gonderiniz.\n";
}
sendData = newSentence.getBytes();
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,IPAddress, port);
calcServerSocket.send(sendPacket);
45
46
Example 9: DatagramBomber Application
Program Run
Java Ağ Programcılığı, page: 451
>java UDPCalcClient 139.179.198.16 (wrong server IP number)
Lutfen iki adet sayi giriniz:24x10
Paket 1.kez Gonderildi.Cevap Bekleniyor...
Paket 2.kez Gonderildi.Cevap Bekleniyor...
Paket 3.kez Gonderildi.Cevap Bekleniyor...
Cevap alinamadi.
>java UDPCalcClient 139.179.198.17
Lutfen iki adet sayi giriniz:24x10
Paket 1.kez Gonderildi.Cevap Bekleniyor...
Paket alindi. Cevap: 24*10=240
>
47
48
DatagramBomberServer
DatagramBomberClient (1)
import java.io.*;
import java.net.*;
import java.io.*;
import java.net.*;
class DatagramBomberClient {
public static void main(String args[]) throws Exception {
DatagramSocket clientSocket = new DatagramSocket();
String host = "localhost";
if (args.length > 0) {
host = args[0];
}
class DatagramBomberServer {
public static void main(String args[]) throws Exception {
DatagramSocket serverSocket = new DatagramSocket(13579);
byte[] receiveData = new byte[1024];
while (true) {
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
System.out.print("Packet received from " + receivePacket.getAddress());
System.out.print(" port " + receivePacket.getPort());
String sentence = new String(receivePacket.getData(), 0, receivePacket.getLength());
System.out.println(“”+ sentence);
String newSentence;
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
InetAddress IPAddress = InetAddress.getByName(host);
System.out.print("Lutfen isteginizi yaziniz:");
BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in));
String sentence = inFromUser.readLine();
for (int x = 0; x < 500000; x++) {
newSentence = "" + x;
byte[] sendData = newSentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
serverSocket.send(sendPacket);
} //for() son
byte[] sendData = sentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 13579);
clientSocket.send(sendPacket);
System.out.println("Packet Sent.");
int counter = 0;
byte[] receiveData = new byte[65508];
……….
} // while() son
} //main() son
} //sınıf son
49
DatagramBomberClient (2)
50
Output (1)
> java DatagramBomberClient 139.179.198.17
Lutfen isteginizi yaziniz:test
Packet Sent.
Sirasi bozulmus paket. Gelen:1 Beklenen:0
Sirasi bozulmus paket. Gelen:0 Beklenen:1
Sirasi bozulmus paket. Gelen:6 Beklenen:2
Sirasi bozulmus paket. Gelen:7 Beklenen:3
Sirasi bozulmus paket. Gelen:2 Beklenen:4
Sirasi bozulmus paket. Gelen:3 Beklenen:5
Sirasi bozulmus paket. Gelen:8 Beklenen:6
Sirasi bozulmus paket. Gelen:9 Beklenen:7
Sirasi bozulmus paket. Gelen:4 Beklenen:8
Sirasi bozulmus paket. Gelen:10 Beklenen:9
Sirasi bozulmus paket. Gelen:11 Beklenen:10
Sirasi bozulmus paket. Gelen:5 Beklenen:11
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
5 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 9
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 11
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 13
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 15
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 17
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 19
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
………..
while (true) {
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
String recStr = new String(receivePacket.getData(), 0, receivePacket.getLength());
if (!recStr.equalsIgnoreCase(new String("" + counter))) {
System.out.print("Sirasi bozulmus paket. Gelen:" + recStr);
System.out.println(" Beklenen:" + counter);
} else {
System.out.print(recStr + " ");
}
counter++;
} // while() son
} // main() son
} // sınıf son
Sirasi bozulmus paket. Gelen:579 Beklenen:213
Sirasi bozulmus paket. Gelen:1008 Beklenen:214
Sirasi bozulmus paket. Gelen:1257 Beklenen:215
Sirasi bozulmus paket. Gelen:1513 Beklenen:216
Sirasi bozulmus paket. Gelen:1743 Beklenen:217
...
Sirasi bozulmus paket. Gelen:489817 Beklenen:753
Sirasi bozulmus paket. Gelen:492146 Beklenen:754
Sirasi bozulmus paket. Gelen:493147 Beklenen:755
Sirasi bozulmus paket. Gelen:493702 Beklenen:756
Sirasi bozulmus paket. Gelen:495686 Beklenen:757
Sirasi bozulmus paket. Gelen:498063 Beklenen:758
51
52
UDP and TCP Comparison
UDP vs. TCP
We begin by listing the main functions of the TCP protocol:
• Packet ordering: TCP delivers IP packets in the order transmitted,
through sequencing.
• In summary, the TCP provides a useful service to applications
that need to exchange relatively large amounts of data in a
reliable manner and without real-time delivery constraints.
• Reliable transmission: Lost packets are detected and recovered
through retransmission.
• Streaming abstraction: The abstraction of a continuous
bidirectional communications byte-stream between two entries
(data packets are delivered reliably and in the order transmitted)
The UDP protocol does not have all these features.
• Flow control: The receiver can slow down the server if data is
received at a rate that exceeds the receiver’s processing capacity.
• It is therefore suitable for applications fitting different criteria.
• The UDP protocol provides a less reliable, packet based
service without support for flow or congestion control.
• Congestion control: TCP implements a distributed congestion
control algorithm that slows down individual stream transmission if
packet loss (network traffic) is detected. The algorithm is tuned to
provide fair sharing of network resources among TCP streams.
53
Java UDP Support
54
UDP Based Communication
• The DatagramPacket, DatagramSocket and MulticastSocket
classes in the java.net package implement system-independent
datagram communication using UDP.
• An application can send and receive DatagramPackets through a
DatagramSocket.
• In addition, DatagramPackets can be broadcast to multiple
recipients all listening to a MulticastSocket. (Chapter 12 in our
book).
RTP and JMF
server/
client
server
application
process
DatagramPacket
DatagramSocket
socket at a well-known port
used for all communication
operating
system
The process (thread) structure of a UDP server or UDP client
• RTP (Real Time Protocol) is an unreliable end-to-end application
layer protocol based on UDP datagram protocol providing
sequencing, time stamping, and data-source information.
• iterative, connectionless
• There is no notion of a server socket. The same socket,
DatagramSocket, is used to send data and to listen for incoming
connections.
• The Java Media Framework (JMF) extension provides support for
the RTP and other multimedia protocols.
55
56
Individual Datagram Packets vs
TCP Stream Based Network Connection
Connectionless Communication
• Although TCP ultimately packetizes the data you send, TCP sockets
allow you to treat a network connection as a stream; you send and
receive with input and output streams that you get from the socket.
No Connection between two hosts and
• UDP doesn't allow this; you always work with individual datagram
packets.
• UDP doesn't have any concept of a connection between
two hosts; it only knows about individual datagrams.
• All the data you stuff into a single datagram is sent as a single packet,
and is lost as a group.
• Figuring out who sent what data is the application's
responsibility.
Data from Many Hosts
• A single DatagramSocket can receive data from many
independent hosts. The socket isn't dedicated to a single
connection, as it is in TCP.
57
References
1. Computer Networking: A Top-Down Approach Featuring the Internet,
6th Edition, J. F. Kurose, K. W. Ross, Addison Wesley, 2011.
2. Java Ağ Programcılığı, (Chapters: 10-11), H. Gümüşkaya, Ö. Boyacı,
ALFA, 2003.
3. Java Network Programming (2nd Edition), E. R. Harold, 731 pages,
O’Reilly, 2000.
4. Beginning Java Networking, Chad Darby, …, 900 pages, Wrox Pres,
2001.
5. “All About Sockets” (Sun tutorial), http://www.javaworld.com/javaworld/jw12-1996/jw-12-sockets.html
6. “Socket Programming in Java: a tutorial,”
http://www.javaworld.com/javaworld/jw-12-1996/jw-12-sockets.html
7. C-language tutorial (audio/slides): “Unix Network Programming” (J.
Kurose) http://manic.cs.umass.edu/~amldemo/courseware/intro.
59
58

Benzer belgeler

Soket Haberleşme

Soket Haberleşme java.io paketinde yer alan giriş/çıkış sınıfları olan Reader, Writer, InputStream, OutputStream kullanılarak gerçekleştirilir. Kod Listesi 11.5: Java’da soket Sunucu kodu package com.example; impor...

Detaylı