UDP客户端程序,用于对服务端发送数据,并接收服务端的回应信息.,话不多说 show me your code!
import java.io.*; import java.net.*;
public class SyslogClient { private byte[] buffer = new byte[1024]; private DatagramSocket ds = null;
public SyslogClient() throws Exception { ds = new DatagramSocket(); }
public final void setSoTimeout(final int timeout) throws Exception { ds.setSoTimeout(timeout); }
public final int getSoTimeout() throws Exception { return ds.getSoTimeout(); } public final DatagramSocket getSocket() { return ds; }
public final String receive(final String lhost, final int lport) throws Exception { DatagramPacket dp = new DatagramPacket(buffer, buffer.length); ds.receive(dp); String info = new String(dp.getData(), 0, dp.getLength()); return info; }
public final void close() { try { ds.close(); } catch (Exception ex) { ex.printStackTrace(); } }
public final DatagramPacket send(final String host, final int port, final byte[] bytes) throws IOException { DatagramPacket dp = new DatagramPacket(bytes, bytes.length, InetAddress .getByName(host), port); ds.send(dp); return dp; }
public static void main(String[] args) throws Exception { SyslogClient client = new SyslogClient(); String serverHost = "127.0.0.1"; int serverPort = 514; client.send(serverHost, serverPort, ("什么都可以的接收参数").getBytes()); String info = client.receive(serverHost, serverPort); System.out.println("服务端回应数据:" + info); } }
|