服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|

服务器之家 - 编程语言 - JAVA教程 - Datagram Scoket双向通信

Datagram Scoket双向通信

2019-11-20 15:22Java教程网 JAVA教程

这篇文章主要介绍了Datagram Scoket双向通信,需要的朋友可以参考下

这里是两个人进行通信。是根据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();

  }
 }
}

 

延伸 · 阅读

精彩推荐