這篇文章主要為大家展示了“java如何實(shí)現(xiàn)UDP雙人交互”,內(nèi)容簡而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領(lǐng)大家一起研究并學(xué)習(xí)一下“java如何實(shí)現(xiàn)UDP雙人交互”這篇文章吧。

發(fā)送端
public class my implements Runnable {
private DatagramSocket client ;
private BufferedReader reader;
private String toip; //對方的ip
private int toport; //對方的端口
public my(int port,String toip,int toport)
{
try {
client=new DatagramSocket(port);
reader=new BufferedReader(new InputStreamReader(System.in));
this.toip=toip;
this.toport=toport;
} catch (SocketException e) {
e.printStackTrace();
}
}
public void run()
{
while(true)
{
String s;
try {
s = reader.readLine();
byte[] datas=s.getBytes();
DatagramPacket packet=new DatagramPacket(datas,0,datas.length,new InetSocketAddress(this.toip,this.toport));
client.send(packet);
if(s.equals("bye"))
{
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
client.close();
}
}接收端:使用面向?qū)ο蠓庋b
public class you implements Runnable{
private DatagramSocket server;
private int port;
private String from;
public you(int port,String from)
{
this.port=port;
this.from=from;
try {
server=new DatagramSocket(port);
} catch (SocketException e) {
e.printStackTrace();
}
}
public void run()
{
while(true)
{
byte[] container=new byte[1024*60];
DatagramPacket packet=new DatagramPacket(container,0,container.length);
try {
server.receive(packet);
byte[] datas=packet.getData();
int len=packet.getLength();
String data=new String(datas,0,datas.length);
System.out.println(from+":"+data);
if(data.equals("bye"))
{
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
server.close();
}
}加入多線程實(shí)現(xiàn)雙向交流
public class student {
public static void main(String[]args)
{
new Thread(new my(9999,"localhost",8888)).start();//發(fā)送
new Thread(new you(7777,"teacher")).start(); //接收
}
}
public class teacher {
public static void main(String[]args)
{
new Thread(new you(8888,"student")).start();//接收
new Thread(new my(5555,"localhost",7777) ).start();//發(fā)送
}
}以上是“java如何實(shí)現(xiàn)UDP雙人交互”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學(xué)習(xí)更多知識,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!
另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內(nèi)外云服務(wù)器15元起步,三天無理由+7*72小時售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國服務(wù)器、虛擬主機(jī)、免備案服務(wù)器”等云主機(jī)租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡單易用、服務(wù)可用性高、性價比高”等特點(diǎn)與優(yōu)勢,專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應(yīng)用場景需求。
文章名稱:java如何實(shí)現(xiàn)UDP雙人交互-創(chuàng)新互聯(lián)
鏈接URL:http://chinadenli.net/article14/cohede.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供ChatGPT、App設(shè)計(jì)、Google、電子商務(wù)、品牌網(wǎng)站制作、搜索引擎優(yōu)化
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容