Datagram Scoket雙向通信
這里是兩個人進行通信。是根據(jù)ip來判斷的,xp與xp之間沒有問題,我win7和xp有問題(已解決 關閉防火墻,如果是內(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)絡程序
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();
}
}
}
相關文章
為什么rest接口返回json建議采用下劃線形式,不要用駝峰
為什么rest接口返回json建議采用下劃線形式,不要用駝峰?今天小編就來為大家說明一下原因,還等什么?一起跟隨小編過來看看吧2020-09-09Java后臺防止客戶端重復請求、提交表單實現(xiàn)原理
這篇文章主要介紹了Java后臺防止客戶端重復請求、提交表單實現(xiàn)原理,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2019-12-12Java開發(fā)中讀取XML與properties配置文件的方法
這篇文章主要介紹了Java開發(fā)中讀取XML與properties配置文件的方法,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2017-01-01