当前位置:主页 > 软件编程 > JAVA代码 >

Datagram Scoket双向通信

时间:2020-10-01 15:47:11 | 栏目:JAVA代码 | 点击:

这里是两个人进行通信。是根据ip来判断的,xp与xp之间没有问题,我win7和xp有问题(已解决 关闭防火墙,如果是内网 网段要一致)

复制代码 代码如下:

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();//配置监听程序 必须放在前面

  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(); // 必须加break 否者还会有回车信号 break;
   }

  }

 }

 static void send(String str) {
  // UDP网络程序
  DatagramSocket ds = null;
  DatagramPacket dp = null;
  try {
   ds = new DatagramSocket(3000);//打开端口号
  } 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);//打开端口
   } 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();

  }
 }
}

您可能感兴趣的文章:

相关文章