Java IO复习 UDP
Posted 不被女生喜欢好多年
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java IO复习 UDP相关的知识,希望对你有一定的参考价值。
客户端:
package cn.zyw.javaurl; import java.io.IOException; import java.net.*; /** * Created by zyw on 2016/4/2. */ public class UDPClient { public static void main(String args[]){ try { DatagramSocket clientsocket=new DatagramSocket(); String senddata="hello my name is zyw"; byte[] bytes=senddata.getBytes(); InetAddress ip=InetAddress.getByName("127.0.0.1"); DatagramPacket packet=new DatagramPacket(bytes,0,senddata.length(),ip,7777); clientsocket.send(packet); byte data[]=new byte[1024]; DatagramPacket packet1=new DatagramPacket(data,0,data.length); clientsocket.receive(packet1); String s=new String(data,0,packet1.getLength()); System.out.println("server say:"+s); } catch (SocketException e) { e.printStackTrace(); } catch (UnknownHostException e) { e.printStackTrace(); }catch (IOException e) { e.printStackTrace(); } } }
服务器:
package cn.zyw.javaurl; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; /** * Created by zyw on 2016/4/2. */ public class UDPServer { public static void main(String args[]){ try { DatagramSocket serversocket=new DatagramSocket(7777); byte[] data=new byte[1024]; DatagramPacket packet=new DatagramPacket(data,data.length); System.out.println("服务器已启动......"); serversocket.receive(packet); String s=new String(data,0,packet.getLength()); System.out.println("get client:"+s); DatagramSocket clientsocket=new DatagramSocket(); String senddata="welcome to you visit "; byte[] bytes=senddata.getBytes(); InetAddress ip=packet.getAddress(); int port=packet.getPort(); DatagramPacket p=new DatagramPacket(bytes,0,senddata.length(),ip,port); clientsocket.send(p); } catch (SocketException e) { e.printStackTrace(); }catch (IOException e) { e.printStackTrace(); } } }
以上是关于Java IO复习 UDP的主要内容,如果未能解决你的问题,请参考以下文章
java缓冲字符字节输入输出流:java.io.BufferedReaderjava.io.BufferedWriterjava.io.BufferedInputStreamjava.io.(代码片段