Datagram Scoket雙向通訊。本站提示廣大學習愛好者:(Datagram Scoket雙向通訊)文章只能為提供參考,不一定能成為您想要的結果。以下是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();
}
}
}