根据老师代码,在IDEA上写的,想写一直可以循环问答下去的,可惜学艺不精,调试了一个小时还没写好(太菜了)
package com.zyc.net;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class AnswersServer {
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(9000);
while(true){
Socket s = ss.accept();
InputStreamReader inputStreamReader = new InputStreamReader(s.getInputStream());
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String request = bufferedReader.readLine();
System.out.println("接收到了客户端的问题:" + request);
PrintWriter printWriter = new PrintWriter(s.getOutputStream());
System.out.println("请输入回答");
Scanner sc = new Scanner(System.in);
String info = sc.next();
//String advice = "I am Server";
printWriter.println(info);
printWriter.close();
}
}
}
class QuestionClient{
public static void main(String[] args) throws UnknownHostException, IOException {
//向服务器端发送请求,服务器IP地址和服务器监听的端口号
Socket client = new Socket("localhost",9000);
//通过printWriter 来向服务器发送消息
PrintWriter printWriter = new PrintWriter(client.getOutputStream());
System.out.println("连接已建立...");
//发送消息
System.out.println("请提出问题");
Scanner sc = new Scanner(System.in);
String info = sc.nextLine();
printWriter.println(info);
printWriter.flush();
InputStreamReader streamReader = new InputStreamReader(client.getInputStream());
//链接数据串流,建立BufferedReader来读取,将BufferReader链接到InputStreamReder
BufferedReader reader = new BufferedReader(streamReader);
String advice = reader.readLine();
System.out.println("接受到服务器的回答"+advice);
reader.close();
}
}
运行结果(每一步,一张图)
初始状态(客户端)
输入问题(客户端)
接收问题(服务端)
回答问题(服务端)
接收回答(客户端)