多次交互的Client端
public class Client {
public static void main(String[] args) throws Exception{
Socket client = new Socket("127.0.0.1",8888);
PrintStream out = new PrintStream(client.getOutputStream(),true);
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
Console console = System.console();
String line1 = console.readLine();
while(line1!=null){
out.println(line1);
line1 = console.readLine();
}
String line2 = in.readLine();
System.out.println(line2);
out.close();
in.close();
}
}
加入多线程功能
public class Process implements Runnable {
private Socket socket;
public Process(Socket socket){
this.socket = socket;
}
@Override
public void run() {
try {
PrintStream out = new PrintStream(socket.getOutputStream(),true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out.println("gun");
String line = in.readLine();
while(line!=null){
line = in.readLine();
System.out.println(line);
}
out.close();
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Server端
public class Server {
public static void main(String[] args) throws Exception {
ServerSocket server = new ServerSocket(8888);
while(true){
Socket socket = server.accept();
Process pro = new Process(socket);
Thread th = new Thread(pro);
th.start();
}
}
}