Datagram Scoket双向通信
Datagram Scoket双向通信
发布时间:2016-12-28 来源:查字典编辑
摘要:这里是两个人进行通信。是根据ip来判断的,xp与xp之间没有问题,我win7和xp有问题(已解决关闭防火墙,如果是内网网段要一致)复制代码代...

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

}

}

}

推荐文章
猜你喜欢
附近的人在看
推荐阅读
拓展阅读
相关阅读
网友关注
最新Java学习
热门Java学习
编程开发子分类