java UDP传输
程序员文章站
2022-04-08 23:18:27
...
TCP通过 ServerSocket 和 Socket 来实现传输
UDP主要通过 DatagramSocket 和 DatagramPacket 来完成传输
直接上代码
服务器端:
客户端:
UDP主要通过 DatagramSocket 和 DatagramPacket 来完成传输
直接上代码
服务器端:
# public class UdpServer # { # private DatagramSocket server; # # private DatagramPacket packet; # # private byte[] b; # # private String str; # # public UdpServer() # { # Init(); # } # # private void Init() # { # # b = new byte[1024]; # # receive(); # } # # private void receive() # { # try # { # server=new DatagramSocket(11111); //绑定11111端口 # # while(true) # { # packet = new DatagramPacket(b, b.length); # # server.receive(packet); //接收数据包 # # int i = packet.getLength(); # # if(i>0) //数据包有内容,就打印出接收到的数据 # { # str = new String(b, 0, i); # System.out.println("接收到的字符 == " + str); # packet = null; # } # } # }catch(SocketException e) # { # e.printStackTrace(); # }catch(IOException e) # { # e.printStackTrace(); # }finally # { # server.close(); # } # } # # public static void main(String[] args) # { # new UdpServer(); # } # }
客户端:
# public class UdpClient # { # private DatagramSocket client; # # private DatagramPacket packet; # # private byte b[]; # # public UdpClient() # { # Init(); # } # # private void Init() # { # b = new byte[1024]; # # send(); # } # # private void send() # { # try # { # client = new DatagramSocket(); # # b = "UDP数据发送".getBytes(); //发送给服务器端的数据 # # packet = new DatagramPacket(b, b.length, new InetSocketAddress("127.0.0.1", 11111)); //绑定服务器 # client.send(packet); //发送数据包 # } catch (SocketException e) # { # e.printStackTrace(); # } catch (IOException e) # { # e.printStackTrace(); # } finally # { # client.close(); # } # } # # public static void main(String[] args) # { # new UdpClient(); # } # }
上一篇: java ftp操作
下一篇: tomcat一闪而过启动失败
推荐阅读
-
浅析Java中Apache BeanUtils和Spring BeanUtils的用法
-
深入理解Java设计模式之组合模式
-
文件上传输入框的value值有没有意义?
-
使用java打印所有的水仙花数
-
弹窗时解决错误java.lang.IllegalArgumentException: Window type can not be changed after the window is added.
-
IDEA中add framework support时缺少Spring,Java EE等框架支持
-
java设计模式(实战)-责任链模式
-
Java之HashMap源码分析(第五篇:访问元素)
-
详解Java匿名内部类
-
项目js java 实现自动复制粘贴 亲测有效