Java UDP 网络编程 示例 -Java学习笔记(30)

 Java UDP网络编程主要通过 DatagramSocketDatagramPacket 两个类实现的,下面是一个示例程序,
Server监听UDP 2000端口并把收到的Long类型数值打印出来
Client则通过输入获得Long类型的数值,并把它发给Server

Server:

/* Coding by nyzhl */
import  java.net. * ;
import  java.io. * ;

public   class  DatagramServer  {
    
public static void main (String[] args) {
        DatagramSocket ds 
= null;
        
try {
            ds 
= new DatagramSocket(2000);
        }

        
catch (SocketException e) {
            e.printStackTrace();
            System.exit(
-1);
        }

        
byte[] buffer = new byte[1024];
        DatagramPacket dp 
= new DatagramPacket(buffer,buffer.length);
        
while (true{
            DataInputStream in 
= new DataInputStream (
                
new ByteArrayInputStream (buffer)
            );
            
try {
                ds.receive(dp);
                System.out.println(in.readLong());
                in.close();
            }

            
catch (IOException e) {
                e.printStackTrace();
                
continue;
            }

        }

        
//ds.close(); JDK提示"无法访问的语句"
        
//因为前面是死循环,无论如何也执行不到后面的语句
    }

}

Client:

/* coding by nyzhl */
import  java.net. * ;
import  java.io. * ;

public   class  DatagramClient  {
    
public static void main (String[] args) {
        DatagramSocket ds 
= null;
        
try {
            ds 
= new DatagramSocket();
        }

        
catch (SocketException e) {
            e.printStackTrace();
            System.exit(
-1);
        }

        BufferedReader typeReader 
= new BufferedReader (
            
new InputStreamReader(System.in)
        );
        
long data = 0;
        
while(true{
            ByteArrayOutputStream bytesOut 
= new ByteArrayOutputStream(); 
            DataOutputStream dataOut 
= new DataOutputStream (bytesOut);
            
try {
                data 
= Long.parseLong(typeReader.readLine());
                dataOut.writeLong(data);
                dataOut.flush();
                
byte[] buffer = bytesOut.toByteArray();
                DatagramPacket dp 
= new DatagramPacket(
                    buffer,
                    buffer.length,
                    
new InetSocketAddress("127.0.0.1",2000)
                );
                ds.send(dp);
                dataOut.close();
                bytesOut.close();
            }

            
catch (SocketException e) {
                System.err.println(
"Socket Error!");
                
continue;
            }

            
catch (IOException e) {
                System.err.println(
"IO Error!");
                
continue;
            }

            
catch (Exception e) {
                e.printStackTrace();
                
continue;
            }

        }

        
//ds.close(); JDK提示"无法访问的语句"
        
//因为前面是死循环,无论如何也执行不到后面的语句
    }

}

 

下面参看API文档
Class DatagramSocket:

Constructor Summary
 DatagramSocket()
          Constructs a datagram socket and binds it to any available port on the local host machine.
protected DatagramSocket(DatagramSocketImpl impl)
          Creates an unbound datagram socket with the specified DatagramSocketImpl.
 DatagramSocket(int port)
          Constructs a datagram socket and binds it to the specified port on the local host machine.
 DatagramSocket(int port, InetAddress laddr)
          Creates a datagram socket, bound to the specified local address.
 DatagramSocket(SocketAddress bindaddr)
          Creates a datagram socket, bound to the specified local socket address.

 

Method Summary
 voidbind(SocketAddress addr)
          Binds this DatagramSocket to a specific address & port.
 voidclose()
          Closes this datagram socket.
 voidconnect(InetAddress address, int port)
          Connects the socket to a remote address for this socket.
 voidconnect(SocketAddress addr)
          Connects this socket to a remote socket address (IP address + port number).
 voiddisconnect()
          Disconnects the socket.
 booleangetBroadcast()
          Tests if SO_BROADCAST is enabled.
 DatagramChannelgetChannel()
          Returns the unique DatagramChannel object associated with this datagram socket, if any.
 InetAddressgetInetAddress()
          Returns the address to which this socket is connected.
 InetAddressgetLocalAddress()
          Gets the local address to which the socket is bound.
 intgetLocalPort()
          Returns the port number on the local host to which this socket is bound.
 SocketAddressgetLocalSocketAddress()
          Returns the address of the endpoint this socket is bound to, or null if it is not bound yet.
 intgetPort()
          Returns the port for this socket.
 intgetReceiveBufferSize()
          Get value of the SO_RCVBUF option for this DatagramSocket, that is the buffer size used by the platform for input on this DatagramSocket.
 SocketAddressgetRemoteSocketAddress()
          Returns the address of the endpoint this socket is connected to, or null if it is unconnected.
 booleangetReuseAddress()
          Tests if SO_REUSEADDR is enabled.
 intgetSendBufferSize()
          Get value of the SO_SNDBUF option for this DatagramSocket, that is the buffer size used by the platform for output on this DatagramSocket.
 intgetSoTimeout()
          Retrieve setting for SO_TIMEOUT.
 intgetTrafficClass()
          Gets traffic class or type-of-service in the IP datagram header for packets sent from this DatagramSocket.
 booleanisBound()
          Returns the binding state of the socket.
 booleanisClosed()
          Returns whether the socket is closed or not.
 booleanisConnected()
          Returns the connection state of the socket.
 voidreceive(DatagramPacket p)
          Receives a datagram packet from this socket.
 voidsend(DatagramPacket p)
          Sends a datagram packet from this socket.
 voidsetBroadcast(boolean on)
          Enable/disable SO_BROADCAST.
static voidsetDatagramSocketImplFactory(DatagramSocketImplFactory fac)
          Sets the datagram socket implementation factory for the application.
 voidsetReceiveBufferSize(int size)
          Sets the SO_RCVBUF option to the specified value for this DatagramSocket.
 voidsetReuseAddress(boolean on)
          Enable/disable the SO_REUSEADDR socket option.
 voidsetSendBufferSize(int size)
          Sets the SO_SNDBUF option to the specified value for this DatagramSocket.
 voidsetSoTimeout(int timeout)
          Enable/disable SO_TIMEOUT with the specified timeout, in milliseconds.
 voidsetTrafficClass(int tc)
          Sets traffic class or type-of-service octet in the IP datagram header for datagrams sent from this DatagramSocket.


Class DatagramPacket:

Constructor Summary
DatagramPacket(byte[] buf, int length)
          Constructs a DatagramPacket for receiving packets of length length.
DatagramPacket(byte[] buf, int length, InetAddress address, int port)
          Constructs a datagram packet for sending packets of length length to the specified port number on the specified host.
DatagramPacket(byte[] buf, int offset, int length)
          Constructs a DatagramPacket for receiving packets of length length, specifying an offset into the buffer.
DatagramPacket(byte[] buf, int offset, int length, InetAddress address, int port)
          Constructs a datagram packet for sending packets of length length with offset ioffsetto the specified port number on the specified host.
DatagramPacket(byte[] buf, int offset, int length, SocketAddress address)
          Constructs a datagram packet for sending packets of length length with offset ioffsetto the specified port number on the specified host.
DatagramPacket(byte[] buf, int length, SocketAddress address)
          Constructs a datagram packet for sending packets of length length to the specified port number on the specified host.
 
Method Summary
 InetAddressgetAddress()
          Returns the IP address of the machine to which this datagram is being sent or from which the datagram was received.
 byte[]getData()
          Returns the data buffer.
 intgetLength()
          Returns the length of the data to be sent or the length of the data received.
 intgetOffset()
          Returns the offset of the data to be sent or the offset of the data received.
 intgetPort()
          Returns the port number on the remote host to which this datagram is being sent or from which the datagram was received.
 SocketAddressgetSocketAddress()
          Gets the SocketAddress (usually IP address + port number) of the remote host that this packet is being sent to or is coming from.
 voidsetAddress(InetAddress iaddr)
          Sets the IP address of the machine to which this datagram is being sent.
 voidsetData(byte[] buf)
          Set the data buffer for this packet.
 voidsetData(byte[] buf, int offset, int length)
          Set the data buffer for this packet.
 voidsetLength(int length)
          Set the length for this packet.
 voidsetPort(int iport)
          Sets the port number on the remote host to which this datagram is being sent.
 voidsetSocketAddress(SocketAddress address)
          Sets the SocketAddress (usually IP address + port number) of the remote host to which this datagram is being sent.

 
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值