Udp簡單的服務器與客戶端07

UDP協議:
UDP協議傳輸數據是不可靠的,在java中,java.util.DatagramSocket負責接收和發送UDP數據報,java.util.DatagramPacket表示UDP數據表。每一個
DatagramSocket與一個本底地址綁定,每一個DatagramSocket能夠把UDP數據報發送給任意一個遠程DatagramSocket,也能夠接收來自任意一個遠程的
DatagramSocket的UDP數據報。在UDP數據報中包含了目的地址信息,DatagramSocket根據該信息把數據報發送到目的地java

UDP服務端socket

public class EchoServer{ private int port = 8089; private DatagramSocket socket; public EchoServer()throws IOException{ socket = new DatagramSocket(port); System.out.println("服務端啓動"); } public String ehco(String msg){ return "ehco:"+msg; } public void service(){ while(true){ try { //建立一個數據報對象 DatagramPacket packet = new DatagramPacket(new byte[512], 512); socket.receive(packet);//接收來自任意一個EhcoClient的數據報 String msg = new String(packet.getData(), 0, packet.getLength()); System.out.println(packet.getAddress()+":"+packet.getPort()+">"+msg); packet.setData(ehco(msg).getBytes());//給EchoClient發送數據報  socket.send(packet); } catch (Exception e) { e.printStackTrace(); } } } public static void main(String[] args) throws IOException { new EchoServer().service(); } }

UDP客戶端spa

public class EchoClient { private String remoteHost = "localhost"; private int remotePort = 8089; private DatagramSocket socket; public EchoClient() throws SocketException{ socket = new DatagramSocket();//與本地任意的端口綁定  } public void talk() throws IOException{ try{ //獲取服務端ip地址 InetAddress remoteIP = InetAddress.getByName(remoteHost); BufferedReader localReader = new BufferedReader(new InputStreamReader(System.in)); String msg = null; while((msg = localReader.readLine()) != null){ byte[] outputData = msg.getBytes(); DatagramPacket outputPacket = new DatagramPacket( outputData, outputData.length,remoteIP,remotePort); socket.send(outputPacket);//發送數據報  DatagramPacket inputPacket = new DatagramPacket(new byte[512], 512); socket.receive(inputPacket);//接收EchoServer的數據報 System.out.println(new String(inputPacket.getData(),0,inputPacket.getLength())); if(msg.equals("bye")){ break; } } }catch (Exception e) { e.printStackTrace(); }finally{ socket.close(); } } public static void main(String[] args) throws SocketException, IOException { new EchoClient().talk(); } }
相關文章
相關標籤/搜索