public void service() {
while (true) {
Socket socket=null;
try {
socket = serverSocket.accept(); //等待客户连接
System.out.println("New connection accepted "
+socket.getInetAddress() + ":" +socket.getPort());
BufferedReader br =getReader(socket);
PrintWriter pw = getWriter(socket);
String msg = null;
while ((msg = br.readLine()) != null) {
System.out.println(msg);
pw.println(echo(msg));
if (msg.equals("bye")) //如果客户发送的消息为“bye”,就结束通信
break;
}
}catch (IOException e) {
e.printStackTrace();
}finally {
try{
if(socket!=null)socket.close(); //断开连接
}catch (IOException e) {e.printStackTrace();}
}
}
}
public static void main(String args[])throws IOException {
new EchoServer().service();
}
}
EchoServer类最主要的方法为service()方法,它不断等待客户的连接请求,当serverSocket.accept()方法返回一个Socket对象,就意味着与一个客户建立了连接。接下来从Socket对象中得到输出流和输入流,并且分别用PrintWriter和BufferedReader来装饰它们。然后不断调用BufferedReader的readLine()方法读取客户发来的字符串XXX,再调用PrintWriter的println()方法向客户返回字符串echo:XXX。当客户发来的字符串为“bye”,就会结束与客户的通信,调用socket.close()方法断开连接。
2.创建EchoClient
在EchoClient程序中,为了与EchoServer通信,需要先创建一个Socket对象:
String host="localhost";
String port=8000;
Socket socket=new Socket(host,port);
在以上Socket的构造方法中,参数host表示EchoServer进程所在的主机的名字,参数port表示EchoServer进程监听的端口。当参数host的取值为“localhost”,表示EchoClient与EchoServer进程运行在同一个主机上。如果Socket对象成功创建,就表示建立了EchoClient与EchoServer之间的连接。接下来,EchoClient从Socket对象中得到了输出流和输入流,就能与EchoServer交换数据。
EchoClient的核心代码如下:
import java.net.*;
import java.io.*;
import java.util.*;
public class EchoClient {
private String host="localhost";
private int port=8000;
private Socket socket;
public EchoClient()throws IOException{
socket=new Socket(host,port);
}
public static void main(String args[])throws IOException{
new EchoClient().talk();
}
|