//服务器端:
import java.io.*;
import java.util.Scanner;
import java.net.ServerSocket;
import java.net.Socket;
class EchoThread implements Runnable{
private Socket client;
public EchoThread(Socket client){
this.client=client;
}
public void run(){
try{
Scanner in=new Scanner(client.getInputStream());
PrintStream out=new PrintStream(client.getOutputStream());
boolean flag=true;
String str;
while(flag){
if(in.hasNext()){
str=in.next().trim();
if(str.equalsIgnoreCase("byebye")){
flag=false;
}
else
out.println("Echo"+str);
}
}
client.close();
out.close();
in.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
public class lab01{
public static void main(String args[]) throws Exception{
ServerSocket ser=new ServerSocket(9999);
boolean flag=true;
while(flag){
Socket client=ser.accept();
new Thread(new EchoThread(client)).start();
}
}
}
//客户端
import java.io.*; import java.util.Scanner; import java.net.Socket; public class lab2{ public static void main(String args[]) throws Exception{ Socket client=new Socket("localhost",9999); Scanner scan=new Scanner(System.in); Scanner in=new Scanner(client.getInputStream()); PrintStream out=new PrintStream(client.getOutputStream()); boolean flag=true; String str; while(flag){ str=scan.nextLine(); if(str.equalsIgnoreCase("byebye")){ flag=false; } else out.println(str); if(in.hasNext()){ System.out.println(in.next()); } } scan.close(); in.close(); out.close(); client.close(); } }