仿照例15.5,编写完整的基于数据报的多客户/服务器通信程序
客户端(只能启动一个,这是数据报的规定,但启动多个不会报错):
import java.io.*;
import java.net.*;
public class QuoteClient {
public static void main(String[] args) throws IOException{
DatagramSocket socket=new DatagramSocket();
BufferedReader sin = new BufferedReader(new InputStreamReader(System.in));
String readLine;
InetAddress address=InetAddress.getByName("127.0.0.1");
while(!(readLine = sin.readLine()).equals("bye")) {
byte[] buf = readLine.getBytes();
DatagramPacket packet=new DatagramPacket(buf, buf.length, address, 4445);
socket.send(packet);
buf = new byte[256];
packet=new DatagramPacket(buf,buf.length);
socket.receive(packet);
buf = packet.getData();
String received=new String(buf);
System.out.println("Quote of the Sever: "+received );
}
socket.close();
}
}
服务器 + 线程:
import java.io.*;
import java.net.*;
class QuoteServerThread extends Thread
{
protected DatagramSocket socket=null;
protected BufferedReader in=null;
protected boolean moreQuotes=true;
public QuoteServerThread() throws IOException {
this("QuoteServerThread");
}
public QuoteServerThread(String name) throws IOException {
super(name);
socket=new DatagramSocket(4445);
in= new BufferedReader(new InputStreamReader(System.in));
}
public void run()
{
while(moreQuotes) {
try{
byte[] buf=new byte[256];
DatagramPacket packet=new DatagramPacket(buf,buf.length);
socket.receive(packet);
System.out.println("Client : "+new String(packet.getData()));
String dString= in.readLine();
if(dString.equals("bye")){moreQuotes=false;}
buf=dString.getBytes();
InetAddress address=packet.getAddress();
int port=packet.getPort();
packet=new DatagramPacket(buf,buf.length,address,port);
socket.send(packet);
}catch(IOException e) {
e.printStackTrace();
moreQuotes=false;
}
}
socket.close();
}
}
public class QuoteServer{
public static void main(String args[]) throws java.io.IOException
{
new QuoteServerThread().start();
}
}