服务端Sockets:
import java.net.*;
import java.io.*;
public class EchoSever{
  public static final PORT=7;
  public EchoSever(){
  super();
 }
 public void startEcho(){
 try{
 SeverSocket sever=new ServerSocket(PORT);
System.out.println("Waiting on a client to coonect");
Socket clientSocket=server.accept();
System.out.println("client requested a connection to the echo sever");
BufferReader input=new InputStreamReader(clientSocket.getInputStrea()));
PrintWriter output=new PrintWriter(clientSocket.getOutputStream(),true);
String msg=input.readLine();
System.out.println(Client sent"+msg);
output.println(msg);
System.out.println("echo server exiting...);
client.close();}
catch(IOException ex){
 System.out.println("Failed I/O: "+ex);
 System.exit(1);
}
}
public static void main(String[] args){
 EchoSever echoSever=new EchoServer();
 echoSever.startEcho();
}
}
客户端:
import java.net.*;
import java.io.*;
public class EchoclientExample{
 public static final String HOST="www.gatech.edu";
 public static final int PORT=7;
 public EchoclientExample(){
 super();
}
 public void testEcho(){
 try{
  Socket socket=new Socket(HOST,PORT);
  BufferedReader input=new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter output=new PrintWriter(socket.getOutputStream(),true);
System.out.println("Sending Hello to the echo server");
output.println("Hello");
System.out.println(input.readLine()+"from the echo server");
socket.close();
}
catch(UNknownHostException ex){
 System.out.println("Failed I/O: "+ex);
System.exit(1);
}
}
 public static void main(String[] args){
 EchoClientExample example=new EchoclientExample();
 example.testEcho();
}
}