1.仿照例15.4,编写完整的基于Socket的多客户/服务器通讯程序。
客户端:
import java.io.*;
import java.net.*;
public class TalkClient {
public static void main(String args[]) {
try{
//向本机的4700端口发出客户请求
Socket socket=new Socket("192.168.43.100",8081);
//由系统标准输入设备构造BufferedReader对象
BufferedReader sin=new BufferedReader(new InputStreamReader(System.in));
//由Socket对象得到输出流,并构造PrintWriter对象
PrintWriter os=new PrintWriter(socket.getOutputStream());
//由Socket对象得到输入流,并构造相应的BufferedReader对象
BufferedReader is=new BufferedReader(new
InputStreamReader(socket.getInputStream()));
String readline;
readline=sin.readLine(); //从系统标准输入读入一字符串
while(!readline.equals("bye")){//若从标准输入读入的字符串为 "bye"则停止循环
//将从系统标准输入读入的字符串输出到Server
os.println(readline);
os.flush();//刷新输出流,使Server马上收到该字符串
//在系统标准输出上打印读入的字符串
System.out.println("Client:"+readline);
//从Server读入一字符串,并打印到标准输出上
System.out.println("Server:"+is.readLine());
readline=sin.readLine(); //从系统标准输入读入一字符串
} //继续循环
os.close(); //关闭Socket输出流
is.close(); //关闭Socket输入流
socket.close(); //关闭Socket
}catch(Exception e) {
System.out.println("Error"+e); //出错,则打印出错信息
}
}
}
服务器端:
//MultiTalkServer.java====================================
import java.io.IOException;
import java.net.ServerSocket;
public class MultiTalkServer {
static int clientnum = 0; //静态成员变量,记录当前客户的个数
public static void main(String args[]) throws IOException {
ServerSocket serverSocket = null;
boolean listening = true;
try {
//创建一个ServerSocket在端口4700监听客户请求
serverSocket = new ServerSocket(8081);
} catch (IOException e) {
System.out.println("Could not listen on port:4700.");
//
System.exit(-1); //退出
}
while (listening) { //循环监听
//监听到客户请求,根据得到的Socket对象和客户计数创建并启动服务线程
new ServerThread(serverSocket.accept(), clientnum).start();
clientnum++; //增加客户计数
}
serverSocket.close(); //关闭ServerSocket
}
}
//ServerThread.java=======================================
import java.io.*;
import java.net.*;
public class ServerThread extends Thread{
Socket socket=null; //保存与本线程相关的Socket对象
int clientnum; //保存本进程的客户计数
public ServerThread(Socket socket,int num) { //构造函数
this.socket=socket; //初始化socket变量
clientnum=num+1; //初始化clientnum变量
}
public void run() { //线程主体
try{
String line;
//由Socket对象得到输入流,并构造相应的BufferedReader对象
BufferedReader is=new BufferedReader(new
InputStreamReader(socket.getInputStream()));
//由Socket对象得到输出流,并构造PrintWriter对象
PrintWriter os=new PrintWriter(socket.getOutputStream());
//由系统标准输入设备构造BufferedReader对象
BufferedReader sin=new BufferedReader(new InputStreamReader(System.in));
//在标准输出上打印从客户端读入的字符串
System.out.println("Client "+ clientnum + ":" + is.readLine());
//从标准输入读入一字符串
line=sin.readLine();
while(!line.equals("bye")){//如果该字符串为 "bye",则停止循环
os.println(line);//向客户端输出该字符串
os.flush();//刷新输出流,使Client马上收到该字符串
//在系统标准输出上打印该字符串
System.out.println("Server:"+line);
//从Client读入一字符串,并打印到标准输出上
System.out.println("Client:"+ clientnum +is.readLine());
line=sin.readLine();//从系统标准输入读入一字符串
}//继续循环
os.close(); //关闭Socket输出流
is.close(); //关闭Socket输入流
socket.close(); //关闭Socket
}catch(Exception e){
System.out.println("Error:"+e);//出错,打印出错信息
}
}
}
2.仿照15.5,编写完整的基于数据报的多客户/服务器通讯程序。
客户端程序 QuoteClient.java
import java.io.*;
import java.net.*;
import java.util.*;
public class QuoteClient {
public static void main(String[] args) throws IOException {
if (args.length != 1) {
// 如果启动时没有给出Server的名字,那么输出错误信息并退出
System.out.println("Usage:java QuoteClient <hostname>");
return;
}
DatagramSocket socket = new DatagramSocket();// 建立数据报套接字
byte[] buf = new byte[256]; // 建立缓冲区
// 由命令行给出的第一个参数默认为Server的域名,通过它得到Server的IP信息
InetAddress address = InetAddress.getByName(args[0]);
// 创建DatagramPacket对象
DatagramPacket packet = new DatagramPacket(buf, buf.length, address, 4445);
socket.send(packet); // 发送
// 创建新的DatagramPacket对象,用来接收数据报
packet = new DatagramPacket(buf, buf.length);
socket.receive(packet); // 接收
// 根据接收的字节数组生成相应的字符串
String received = new String(packet.getData());
// 输出生成的字符串
System.out.println("Quote of the Moment:" + received);
socket.close(); // 关闭数据套接字
DatagramSocket socket=new DatagramSocket();//创建数据报套接字
BufferedReader sin = new BufferedReader(new InputStreamReader(System.in));
String readLine;
InetAddress address=InetAddress.getByName("127.0.0.1");//Server的IP信息
while(!(readLine = sin.readLine()).equals("bye")) {
byte[] buf = readLine.getBytes();
//创建DatagramPacket对象
DatagramPacket packet=new DatagramPacket(buf, buf.length, address, 4445);
socket.send(packet); //发送
buf = new byte[256];
//创建新的DatagramPacket对象,用来接收数据报
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(); //关闭数据报套接字
}
}
服务器方程序QuoteServer.java
public class QuoteServer {
public static void main(String args[])throws java.io.IOException{
new QuoteServerThread().start();// 启动一个QuoteServerThread线程
}
}
程序QouteServerThread.java
import java.io.*;
import java.net.*;
import java.util.*;
public class QuoteServerThread extends Thread// 服务器线程
{
protected DatagramSocket socket = null;// DatagramSocket
protected BufferedReader in = null;// Reader
protected boolean moreQuotes = true;// 标志变量。是否继续操作
public QuoteServerThread() throws IOException {//
this("QuoteServerThread");// QuoteServerThread
}
public QuoteServerThread(String name) throws IOException {
super(name); //
socket = new DatagramSocket(4445);// 创建数据报套接字端口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);
// 由缓冲区构建DatagramPacket对象
socket.receive(packet); // 接收数据报
// 输出客户端发送的内容
System.out.println(new String(packet.getData()));
// 从屏幕获取输入内容,作为发送给客户端的内容
String dString = in.readLine();
// 如果是bey,则向客户端发完消息后退出
if (dString.equals("bye")) {
moreQuotes = false;
}
buf = dString.getBytes();// 把String转换成字节数组,以便传送
// 从Client端传来的Packet中得到Client地址
InetAddress address = packet.getAddress();
int port = packet.getPort(); // 端口号
// 根据客户端信息构建DatagramPacket
packet = new DatagramPacket(buf, buf.length, address, port);
socket.send(packet); // 发送数据报
} catch (IOException e) { // 异常处理
e.printStackTrace(); // 输出异常栈信息
moreQuotes = false; // 标志变量置false,以结束循环
}
}
socket.close(); // 关闭数据报套接字
}
}