《Java编程艺术》章节选登。作者:高永强 清华大学出版社 (即将出版)
23.2.5 Datagram编程(2)
如下为利用
Datagram
编写的用户端程序:
//
这个程序存在本书配套资源目录
Ch23
名为
DatagramClientTest.java
import java.io.
*
;
import java.net.
*
;
import java.util.
*
;
public class DatagramClientTest {
public static void main(String[] args) {
try {
DatagramSocket socket = new DatagramSocket();
//
创建
Datagram
插座
byte[] buf = new byte[256]; //
创建缓冲
InetAddress address = InetAddress.getByName("127.0.0.1"); //
利用本地计算机
sending(socket, buf, buf.length, address, 1688);
//
通过端口
1688
发送空邮包
String received = receiving(socket, buf, buf.length);
//
接收服务器邮包
System.out.println(received); //
打印内容,即慰问和提示
Scanner sc = new Scanner(System.in);//
创建键盘输入扫描
while (sc.hasNextLine()) { //
如果有键盘输入,则继续
String line = sc.nextLine(); //
得到键入内容
if (!line.trim().equals("quit")) {//
如果不是停止
buf = new byte[256]; //
清除缓冲
buf = line.getBytes(); //
将键入内容装入缓冲
sending(socket, buf, buf.length, address, 1688);
//
调用发送方法
received = receiving(socket, buf, buf.length);
//
接收服务器发来的邮包
System.out.println(received);//
打印
buf = new byte[256]; //
清除缓冲
sending(socket, buf, buf.length, address, 1688);
//
发送空邮包
received = receiving(socket, buf, buf.length);
//
接收邮件长度信息
System.out.println(received); //
打印这个信息
}
else break; //
中断循环
}
socket.close(); //
关闭
}
catch (IOException e) {
e.printStackTrace();
}
}
//
自定义静态方法发送邮包至服务器
public static void sending(DatagramSocket socket, byte[] buf, int length, InetAddress address, int port) {
DatagramPacket sendPacket = new DatagramPacket(buf, length, address, port);
try {
socket.send(sendPacket); //
调用发送
}catch (IOException e) {
e.printStackTrace();
}
}
//
自定义静态方法接收从服务器发来的邮包
public static String receiving(DatagramSocket socket, byte[] buf, int length) {
DatagramPacket receivePacket = new DatagramPacket(buf, length);
String received = null;
try {
socket.receive(receivePacket); //
调用接收
received = new String(receivePacket.getData(), 0, receivePacket.getLength()); //
得到信息
} catch (IOException e) {
e.printStackTrace();
}
return received;
}
}
可以看到,用户和服务器通过邮包进行通讯和数据传递。当用户需要得到服务器发送过来的信息时,首先发送一个空邮包给服务器,然后服务器利用这个邮包,将数据发还给用户。如果用户需要将发给服务器的信息转换为大写字母时,也首先将这个信息通过邮包发给服务器,经过处理后,服务器利用这个邮包将新内容发还给用户。
如同上一小节讨论过的远程用户
-
服务器运行模拟,将这个例子的用户端代码中本地计算机
IP
地址
127.0.0.1
修改为作为服务器的远程计算机
IP
地址,如
192.168.15.101
,则可进行联网运行。具体步骤可参考上一小节的例子。(续完)