当前位置: 移动技术网 > IT编程>开发语言>Java > Datagram Scoket双向通信

Datagram Scoket双向通信

2019年07月22日  | 移动技术网IT编程  | 我要评论

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

  }
 }
}

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网