该服务器一次只能处理一个客户端请求;
p/**
* 利用Socket进行简单服务端与客户端连接
* 这是服务端
*/
public class EchoServer {
private ServerSocket serverSocket;
private int port = 8088;
//利用构造器启动服务器
public EchoServer()throws Exception{
serverSocket = new ServerSocket(port);
System.out.println("服务器已启动!");
}
//需要向客户端发送的短信
private String ehco(String msg){
return "echo:"+msg;
}
//通过Socket对象获取Io输入流出
private BufferedReader getReader(Socket socket)throws Exception{
InputStream in = socket.getInputStream();
//返回一个字符流对象
return new BufferedReader(new InputStreamReader(in));
}
//通过Socket对象获取IO输出流
private PrintWriter getWriter(Socket socket)throws Exception{
OutputStream out = socket.getOutputStream();
//自动刷新
return new PrintWriter(out,true);
}
//服务器对客户端的请求进行处理
public void service() {
while(true){
Socket socket = null;
try {
//接收客户端请求,产生socket对象进行通信
socket = serverSocket.accept();
System.out.println("获取客户端的url,端口"+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(ehco(msg));
if(msg.equals("bye")){
break;
}
}
}catch (Exception e){
e.printStackTrace();
}
}
}
public static void main(String[] args) throws Exception{
//产生服务器实例,启动服务器
EchoServer echoServer = new EchoServer();
echoServer.service();
}
}
---------------
客户端(单线程的)
public class EchoClient {
private int port = 8088;
private String host = "localhost";
private Socket socket;
//使用构造方法产生Socket实例
public EchoClient()throws Exception{
socket = new Socket(host,port );
}
//根据socket对象产生输出流对象
private BufferedReader getReader(Socket socket)throws Exception{
InputStream in = socket.getInputStream();
return new BufferedReader(new InputStreamReader(in));
}
//根据Socket对象产生输入流对象
private PrintWriter getWriter(Socket socket)throws Exception{
return new PrintWriter(socket.getOutputStream(),true);
}
//客户端处理方法
public void talk(){
try {
BufferedReader br = getReader(socket);
PrintWriter pw = getWriter(socket);
//控制台输入信息
BufferedReader localReader = new BufferedReader(new InputStreamReader(System.in));
String msg = null;
while((msg = localReader.readLine()) != null){
//pw.write(msg);
//不能使用write()方法,使用write()要加上println,然后flush();
//println方法中包含write()+println()方法,构造时自动刷新;
pw.println(msg);
System.out.println(br.readLine());
if(msg.equals("bye")){
break;
}
}
}catch (Exception e){
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception{
EchoClient client = new EchoClient();
client.talk();
}
}