Datagram Scoket雙向通信
這里是兩個(gè)人進(jìn)行通信。是根據(jù)ip來判斷的,xp與xp之間沒有問題,我win7和xp有問題(已解決 關(guān)閉防火墻,如果是內(nèi)網(wǎng) 網(wǎng)段要一致)
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();
}
}
}
相關(guān)文章
spring boot攔截器實(shí)現(xiàn)IP黑名單實(shí)例代碼
本篇文章主要介紹了spring boot攔截器實(shí)現(xiàn)IP黑名單實(shí)例代碼,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-04-04
java設(shè)計(jì)模式-單例模式實(shí)現(xiàn)方法詳解
單例模式,屬于創(chuàng)建類型的一種常用的軟件設(shè)計(jì)模式。通過單例模式的方法創(chuàng)建的類在當(dāng)前進(jìn)程中只有一個(gè)實(shí)例(根據(jù)需要,也有可能一個(gè)線程中屬于單例2021-07-07
Java 使用POI生成帶聯(lián)動下拉框的excel表格實(shí)例代碼
本文通過實(shí)例代碼給大家分享Java 使用POI生成帶聯(lián)動下拉框的excel表格,代碼簡單易懂,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友參考下吧2017-09-09
SpringMVC?RESTFul實(shí)戰(zhàn)案例刪除功能實(shí)現(xiàn)
這篇文章主要為大家介紹了SpringMVC?RESTFul實(shí)戰(zhàn)案例刪除功能實(shí)現(xiàn),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05
Java?Socket編程從零到實(shí)戰(zhàn)詳解(完整實(shí)戰(zhàn)案例)
這篇文章主要介紹了Java?Socket編程從零到實(shí)戰(zhàn)詳解,本文給大家介紹的非常詳細(xì),感興趣的朋友一起看看吧2025-04-04

