国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Java > 正文

Datagram Scoket雙向通信

2019-11-26 15:32:05
字體:
供稿:網(wǎng)友

這里是兩個人進(jìn)行通信。是根據(jù)ip來判斷的,xp與xp之間沒有問題,我win7和xp有問題(已解決 關(guān)閉防火墻,如果是內(nèi)網(wǎng) 網(wǎng)段要一致)

復(fù)制代碼 代碼如下:

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();//配置監(jiān)聽程序 必須放在前面

  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網(wǎng)絡(luò)程序
  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();

  }
 }
}

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 麻阳| 玉门市| 大连市| 鹰潭市| 常德市| 从化市| 诸暨市| 元江| 泰州市| 宣城市| 白玉县| 都昌县| 长葛市| 鄢陵县| 静海县| 吴桥县| 桃园县| 东安县| 丁青县| 广州市| 本溪| 屏山县| 南陵县| 朝阳市| 甘洛县| 大洼县| 茌平县| 梓潼县| 延长县| 潍坊市| 宣恩县| 潼南县| 泾阳县| 波密县| 青神县| 莲花县| 炎陵县| 漯河市| 垦利县| 儋州市| 绿春县|