java中請(qǐng)給出UDP的DatagramSocket通信的例子
UDP(數(shù)據(jù)報(bào))協(xié)議的通信實(shí)例
馬克-to-win:在UDP編程當(dāng)中,技術(shù)上沒有一個(gè)服務(wù)器和客戶端的概念,即沒有類似于TCP中的ServerSocket類,只有主動(dòng)和被動(dòng)之說,客戶端和服務(wù)器都用DatagramSocket(MyPORT)來綁定到一個(gè)端口,發(fā)送和接收dataPacket,它們是對(duì)等的雙方。不過通常來講,先發(fā)送數(shù)據(jù)的被認(rèn)為是客戶端。in UDP, there is no concept of server or client, only active and passive, client and server both use new DatagramSocket(MyPORT) to bind to a port to use the port to send and receive the dataPacket, the counterpart which initially send the dataPacket is deemed as the client. unlike the TCP protocol, there, there is really ServerSocket.
馬克- to-win:馬克 java社區(qū):防盜版實(shí)名手機(jī)尾號(hào): 73203。
UDP通信主要有兩個(gè)類,DatagramPacket是數(shù)據(jù)容器,它攜帶自己來自何處,以及打算去哪里的信息。DatagramSocket用來發(fā)送或接收DatagramPacket。
DatagramPacket不僅需要包含正式的數(shù)據(jù),也要包含網(wǎng)絡(luò)地址以及端口號(hào),以決定它的目的地。
例:2.3.1(客戶端寫,服務(wù)器端讀)
服務(wù)器端:
import java.net.*;
import java.io.*;
import java.util.*;
public class TestMark_to_win {
static final int MyPORT = 1711;
public static void main(String[] args) throws IOException {
byte[] bufreceive = new byte[1000];
DatagramPacket packetreceive = new DatagramPacket(bufreceive,
bufreceive.length);//測(cè)試結(jié)果bufreceive.length是1000
DatagramSocket socket;
socket = new DatagramSocket(MyPORT);
// Block until a datagram appears:
socket.receive(packetreceive);
String stringreceive = new String(packetreceive.getData(), 0,
packetreceive.getLength());
System.out.println(stringreceive);
socket.close();
}
}
客戶端程序:
import java.net.*;
import java.io.*;
import java.util.*;
public class Test {
static final int MyPORT = 1710;
static final int SERVERPORT = 1711;
public static void main(String[] args) throws IOException {
byte[] bufsend = new byte[1000];
DatagramSocket client;
InetAddress destination = InetAddress.getByName("localhost");
client = new DatagramSocket(MyPORT);
bufsend = "java study".getBytes();// string encode to a byte array
DatagramPacket sendpacket = new DatagramPacket(bufsend, bufsend.length,
destination, SERVERPORT);
client.send(sendpacket);
client.close();
}
}
服務(wù)器端輸出:
java study
例:2.3.2(客戶端無限讀寫,服務(wù)器端也無限讀寫)
import java.net.*;
import java.io.*;
import java.util.*;
public class TestMark_to_win {
static final int MyPORT = 1711;
public static void main(String[] args) throws IOException {
byte[] bufreceive = new byte[1000];
byte[] bufsend = new byte[1000];
/* public DatagramPacket(byte[] buf,int length) Constructs a
DatagramPacket for receiving packets of length length. The length
argument must be less than or equal to buf.length.
*/
DatagramPacket packetreceive = new DatagramPacket(bufreceive,
bufreceive.length);
// Can listen & send on the same socket:
/*
* Datagram packets are used to implement a connectionless packet
* delivery service.
*/
DatagramSocket socket;
/*
* This class represents a socket for sending and receiving datagram
* packets. A datagram socket is the sending or receiving point for a
* packet delivery service. DatagramSocket(MyPORT): Constructs a
* datagram socket and binds it to the specified port on the local host
* machine.
*/
socket = new DatagramSocket(MyPORT);
while (true) {
/*
* Receives a datagram packet from this socket. When this method
* returns, the DatagramPacket's buffer is filled with the data
* received. Block until a datagram appears:
*/
socket.receive(packetreceive);
/* public byte[] getData()Returns the data buffer. public int
* getLength() Returns the length of the data to be sent or the
* length of the data received.
*
* public String(byte[] bytes,int offset,int length) Constructs a
* new String by decoding the specified subarray of bytes using the
* platform's default charset.
*/
String stringreceive = new String(packetreceive.getData(), 0,
packetreceive.getLength());
System.out.println(stringreceive);
stringreceive = stringreceive + "coming back from server";
/*
* public byte[] getBytes() Encodes this String into a sequence of
* bytes using the platform's default charset, storing the result
* into a new byte array.
*/
bufsend = stringreceive.getBytes();
/*
* public 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. The length argument must be less than or equal to
* buf.length.
*
* public InetAddress getAddress() Returns the IP address of the
* machine to which this datagram is being sent or from which the
* datagram was received. public int getPort() Returns the port
* number on the remote host to which this datagram is being sent or
* from which the datagram was received.
*/
DatagramPacket echo = new DatagramPacket(bufsend, bufsend.length,
packetreceive.getAddress(), packetreceive.getPort());
socket.send(echo);
}
}
}
以下是客戶端程序:
import java.net.*;
import java.io.*;
import java.util.*;
public class Test {
static final int MyPORT = 1710;
static final int SERVERPORT = 1711;
public static void main(String[] args) throws IOException {
byte[] bufreceive = new byte[1000];
byte[] bufsend = new byte[1000];
DatagramPacket p = new DatagramPacket(bufreceive, bufreceive.length);
DatagramSocket client;
BufferedReader dis = new BufferedReader(
new InputStreamReader(System.in));
/* public static InetAddress getByName(String host) throws
* UnknownHostException: Determines the IP address of a host, given the
* host's name. The host name can either be a machine name, such as
* "java.sun.com", or a textual representation of its IP address. If a
* literal IP address is supplied, only the validity of the address
* format is checked.
*/
InetAddress destination = InetAddress.getByName("localhost");
client = new DatagramSocket(MyPORT);
while (true) {
String str = dis.readLine();
if (str.equals("end"))
break;
bufsend = str.getBytes();// string encode to a byte array
DatagramPacket sendpacket = new DatagramPacket(bufsend,
bufsend.length, destination, SERVERPORT);
client.send(sendpacket);
// Block until a datagram appears:
client.receive(p);
/* p.getData means return the data buffer of the packet,
* String(byte[] bytes, int offset, int length)------ Constructs a
* new String by decoding the specified subarray of bytes using the
* platform's default charset.
*/
String psx = new String(p.getData(), 0, p.getLength());
System.out.println(psx);
}
}
}
客戶端結(jié)果輸出:(eclipse本身有bug,所以我只用英文實(shí)驗(yàn))
java
javacoming back from server
study
studycoming back from server
end
服務(wù)器端結(jié)果輸出:
java
study