Datagram ket two way communication

  • 2020-04-01 03:16:30
  • OfStack

Here are two people writing to each other. According to IP to judge, there is no problem between xp and xp, I win7 and xp have problems (has been resolved to close the firewall, if it is the internal network network segment to be consistent)


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
public class Me {
 public static void main(String[] args) throws IOException {
  new ReciveThread().start();//The configuration listener must come first
  new SendInfo().main(args);
 }
}
class SendInfo {
 public static void main(String[] args) throws IOException {
  BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
  String str = null;
  String lines = "";
  while ((str = bf.readLine()) != null) {
   lines += str;
   if (str.equals("ok")) {
    send(lines);
    lines = "";
   }
   if (str.equals("bye")) {
    bf.close(); //If you have to break, you will get a return signal.
   }
  }
 }
 static void send(String str) {
  //UDP network program
  DatagramSocket ds = null;
  DatagramPacket dp = null;
  try {
   ds = new DatagramSocket(3000);//Start with a slogan
  } catch (SocketException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  try {
   byte[] ip = new byte[] { (byte) 10, 1, 1, (byte) 200 };
   dp = new DatagramPacket(str.getBytes(), str.length(),
     InetAddress.getByAddress(ip), 9000);//faso
  } catch (UnknownHostException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  try {
   ds.send(dp);
   System.out.println("send success");
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  ds.close();
 }
}
class ReciveThread extends Thread {
 public void run() {
  while (true) {
   DatagramSocket ds = null;
   byte[] buf = new byte[1024];
   DatagramPacket dp = null;
   try {
    ds = new DatagramSocket(9000);//Open port
   } catch (SocketException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   dp = new DatagramPacket(buf, 1024);
   try {
    ds.receive(dp);
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   String str = new String(dp.getData(), 0, dp.getLength()) + "from"
     + dp.getAddress().getHostAddress() + ":port" + dp.getPort();
   System.out.println(str);
   ds.close();
  }
 }
}


Related articles: