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();//配置監(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網絡程序
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();
}
}
}
相關文章
spring boot攔截器實現(xiàn)IP黑名單實例代碼
本篇文章主要介紹了spring boot攔截器實現(xiàn)IP黑名單實例代碼,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-04-04
Java 使用POI生成帶聯(lián)動下拉框的excel表格實例代碼
本文通過實例代碼給大家分享Java 使用POI生成帶聯(lián)動下拉框的excel表格,代碼簡單易懂,非常不錯,具有參考借鑒價值,需要的朋友參考下吧2017-09-09
SpringMVC?RESTFul實戰(zhàn)案例刪除功能實現(xiàn)
這篇文章主要為大家介紹了SpringMVC?RESTFul實戰(zhàn)案例刪除功能實現(xiàn),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-05-05
Java?Socket編程從零到實戰(zhàn)詳解(完整實戰(zhàn)案例)
這篇文章主要介紹了Java?Socket編程從零到實戰(zhàn)詳解,本文給大家介紹的非常詳細,感興趣的朋友一起看看吧2025-04-04

