📄 quoteudpserver.java
字号:
import java.net.*;
import java.io.*;
import java.util.*;
public class QuoteUDPServer
{
private static BufferedReader in;
public static void main(String args[])
{
DatagramSocket socket = null;
DatagramPacket packet = null;
boolean moreQuotes = true;
System.out.println("QuoteUDPServer started... ");
try
{
//实例化一个数据报socket
socket = new DatagramSocket(1111);
in = new BufferedReader(new FileReader("one-liners.txt"));
}
catch (FileNotFoundException e)
{
System.err.println("Couldn't open file.");
}
catch(IOException e)
{
System.err.println(e.getMessage());
}
while (moreQuotes)
{
try
{
byte[] buf = new byte[256];
// 生成一个数据报
packet = new DatagramPacket(buf, buf.length);
//接收数据报
socket.receive(packet);
// figure out response
String data = null;
if (in == null)
data = new Date().toString();
else
data = getNextQuote();
buf = data.getBytes();
// 得到接收的数据报的地址
InetAddress address = packet.getAddress();
System.out.println(address.getHostAddress());
//得到接收数据报的端口
int port = packet.getPort();
//生成一个数据报
packet = new DatagramPacket(buf, data.length(), address, port);
//发送数据报
socket.send(packet);
}
catch (IOException e)
{
e.printStackTrace();
moreQuotes = false;
}
}
socket.close();
}
protected static String getNextQuote()
{
String returnValue = null;
try
{
if ((returnValue = in.readLine()) == null)
{
in.close();
returnValue = "No more quotes. Goodbye.";
}
}
catch (IOException e)
{
returnValue = "IOException occurred in server.";
}
return returnValue;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -