I
Änderungen
Pong: socket = new DatagramSocket(port);
main: Objekte nur erzeugen, wenn gebraucht
und ein paar Println sind anders.
import java.net.*;
import java.io.*;
class Ping extends Thread
{
int count;
InetAddress adr;
int port;
byte[] msg = "ping".getBytes();
DatagramSocket socket;
DatagramPacket packet;
Ping(String adr, int port, int count) throws Exception
{
this.adr = InetAddress.getByName(adr);
this.count = count;
msg = "ping".getBytes();
socket = new DatagramSocket();
packet = new DatagramPacket(msg, msg.length, this.adr, port);
}
public void run()
{
try
{
for(int i=0; i < count;)
{
System.out.println("Hallo from ping");
socket.send(packet);
System.out.println(" +++ ping send " + new String(msg) + " +++");
DatagramPacket pong_packet = new DatagramPacket(msg, msg.length);
socket.receive(pong_packet);
if ( new String(pong_packet.getData()).equals("ping") )
{
System.out.println(new String(pong_packet.getData()));
i++;
}
}
socket.close();
}
catch (Exception e){ e.printStackTrace();}
}
}
class Pong extends Thread
{
int count;
InetAddress adr;
int port;
byte[] msg = "pong".getBytes();
DatagramSocket socket;
DatagramPacket packet;
Pong(String adr, int port, int count) throws Exception
{
this.adr = InetAddress.getByName(adr);
this.count = count;
socket = new DatagramSocket(port);
//socket.bind(new InetSocketAddress(port));
packet = new DatagramPacket(msg, msg.length, this.adr, port);
}
public void run()
{
for(int i=0; i < count;)
{
System.out.println("Hallo from pong");
try {
DatagramPacket ping_packet = new DatagramPacket(msg, msg.length);
socket.receive(ping_packet);
System.out.println(" +++ pong data received +++");
if ( new String(ping_packet.getData()).equals("ping") )
{
System.out.println(new String(ping_packet.getData()));
i++;
}
msg = "pong".getBytes();
socket.send(packet);
System.out.println(msg);
}
catch(Exception e) {e.printStackTrace();}
}
socket.close();
}
}
class pingpong
{
// ping/pong count adr port
public static void main(String args[]) throws Exception
{
int count = Integer.parseInt(args[1]);
int port = Integer.parseInt(args[3]);
if ( "ping".equals(args[0]) )
{
Ping ping = new Ping(args[2], port, count);
ping.start();
}
else if ( "pong".equals(args[0]) )
{
Pong pong = new Pong(args[2], port, count);
pong.start();
}
}
}