TCPまたはUDPパケットを送信する。javaで。

UDPかTCPを指定できるようにした。 Clientx.java
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.io.DataOutputStream;
import java.net.Socket;


public class Clientx {
 public static void main(String[] args) throws IOException{
  String sendData = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";

  String Host = args[0];
  Integer DstPort = Integer.parseInt(args[1]);
  int count = Integer.parseInt(args[2]);
  String Proto = args[3];
 
  System.out.println(Proto);

  if (Proto.equals("U")) {
   UDPsend(sendData,Host,DstPort,count);
  }else{
   TCPsend(sendData,Host,DstPort,count);
  }
 }

 public static void UDPsend(String sdata, String host, int dstPort, int count) throws IOException{
  byte[] bdata = sdata.getBytes("UTF-8");
  DatagramSocket sock = new DatagramSocket();
  DatagramPacket packet 
  = new DatagramPacket(bdata, bdata.length, new InetSocketAddress(host,dstPort));


  for(int i=1; i<=count; i++) {  
   sock.send(packet);
   System.out.println("Sent UDP data  "+host+":"+dstPort);
    try{
    Thread.sleep(1000);
   }catch(InterruptedException e){}
  }
  sock.close();//
 }

 public static void TCPsend(String sdata, String host, int dstPort, int count) {
  try{

   for(int i=1; i<=count; i++) {  
    Socket sock = new Socket(host,dstPort);
    DataOutputStream out = new DataOutputStream(sock.getOutputStream());
    out.writeUTF(sdata);
    System.out.println("Sent TCP data  "+host+":"+dstPort);

    out.close();
    sock.close();
     try{
     Thread.sleep(1000);
    }catch(InterruptedException e){}
   }

  }catch(IOException e){
   e.printStackTrace();
  }

 }
}
------------- 

 使い方 

 TCP12345のパケットを5個送信 

java Clientx localhost 12345 5 T 

 UDP12345のパケットを5個送信 

java Clientx localhost 12345 5 U 

 実際は4番目の引数が"U"ならUDP、それ以外だとTCPになる。 

4番目の引数がないと動かない。 

UDPの場合はport unreachableが返ってきてもとりあえず送信はするが、 
TCPの場合受信者がいないと(指定したTCPポートをリッスンしていない)と、 
1回送ってExceptionを吐いて終了してしまう。 

 TCPのサーバも作った。 TCPのサーバ 

 ServerT.java
import java.io.IOException;
import java.io.DataInputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerT {
 public static void main(String[] args) {
  try{
   while(true){
    ServerSocket svSock = new ServerSocket(12345);
    Socket sock = svSock.accept();
    DataInputStream in = new DataInputStream(sock.getInputStream());
    String strData = in.readUTF();
    System.out.println("Received TCP : "+strData);
    in.close();
    svSock.close();
   }
  }catch(IOException e){
   e.printStackTrace();
  }

 }
}
UDP/TCPどっちでも受信できるようにするのはまた今度。