首页 > 代码库 > JAVA的UDP协议交互信息
JAVA的UDP协议交互信息
由于要做app的UDP协议交互,所以就特地学习了下,其实也就类似于java的server和socket,下面就写了个简单的demo
服务端:
package com.test1;import java.io.IOException;import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.InetSocketAddress;import java.net.SocketException;public class UpdServer { private byte[] buff = new byte[1024]; private DatagramPacket dp; private DatagramSocket ds; private InetSocketAddress socketAddress; public UpdServer(String host, int port){ socketAddress = new InetSocketAddress(host, port); try { ds = new DatagramSocket(socketAddress); } catch (SocketException e) { System.out.println("连接失败:" + e.getLocalizedMessage()); e.printStackTrace(); } System.out.println("服务器开启监听..."); } private String receive(String host, int port) { String info = ""; try{ dp = new DatagramPacket(buff, 0, buff.length); ds.receive(dp); info = new String(dp.getData(), 0, dp.getLength()); }catch (Exception e) { e.printStackTrace(); } return info; } public static void main(String[] args) { String host = "127.0.0.1"; int port = 8888; UpdServer server = new UpdServer(host, port); String info = server.receive(host, port); System.out.println(info); //发送信息到客服端 server.send(new String("你好,骚年!")); } private void send(String string) { DatagramPacket dps = new DatagramPacket(buff, 0, buff.length, dp.getAddress(), dp.getPort()); dps.setData(string.getBytes()); try { ds.send(dps); } catch (IOException e) { e.printStackTrace(); } }}
客户端:
package com.test1;import java.io.IOException;import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.InetAddress;import java.net.SocketException;public class UpdClient { private byte[] buff = new byte[1024]; private DatagramPacket dp; private DatagramSocket ds; public UpdClient(){ try { ds = new DatagramSocket(); } catch (SocketException e) { e.printStackTrace(); } } public static void main(String[] args) { UpdClient updClient = new UpdClient(); String host = "127.0.0.1"; int port = 8888; updClient.send(host, port, new String("你好,少年!").getBytes()); //接受 String info = updClient.receive(); System.out.println(info); } private String receive() { DatagramPacket dpr = new DatagramPacket(buff, buff.length); String info = ""; try { ds.receive(dpr); info = new String(dpr.getData(), 0, dpr.getLength()); } catch (IOException e) { e.printStackTrace(); } return info; } private void send(String host, int port, byte[] b) { try{ dp = new DatagramPacket(buff, 0, buff.length, InetAddress.getByName(host), port); dp.setData(b); ds.send(dp); }catch (Exception e) { e.printStackTrace(); } }}
JAVA的UDP协议交互信息
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。