亲宝软件园·资讯

展开

Scoket双向通信 Datagram Scoket双向通信

人气:0
想了解Datagram Scoket双向通信的相关内容吗,在本文为您仔细讲解Scoket双向通信的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点: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();

  }
 }
}

加载全部内容

相关教程
猜你喜欢
用户评论