您好,登錄后才能下訂單哦!
這篇文章主要為大家展示了“java如何實現UDP雙人交互”,內容簡而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領大家一起研究并學習一下“java如何實現UDP雙人交互”這篇文章吧。
發送端
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(); } }
接收端:使用面向對象封裝
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(); } }
加入多線程實現雙向交流
public class student { public static void main(String[]args) { new Thread(new my(9999,"localhost",8888)).start();//發送 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();//發送 } }
以上是“java如何實現UDP雙人交互”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。