客户端输入一串字符串 服务端反序输出 quit退出来学习java socket编程。
1:阻塞模式
一次只能为一个客户端服务,这种使用在实际使用过程中基本没有用处
package com.lei.socket.test;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class SimpleServer {
//启动服务端监听
public void start(){
try{
ServerSocket server = new ServerSocket(port);
Socket client = null;
while(runFlag){
client = server.accept();//阻塞
System.out.println("accept client " + client.getInetAddress().getHostAddress());
handleClient(client);
}
server.close();
}catch(IOException e){
System.out.println("start error");
}
}
//处理客户端请求
public void handleClient(Socket client){
try{
BufferedReader inReader = new BufferedReader(new InputStreamReader(client.getInputStream()));
BufferedWriter outWriter = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
while(true){
outWriter.write("please input String->");
outWriter.flush();
String str = inReader.readLine();
if(str.equalsIgnoreCase("quit")){
outWriter.write("quit ok");
client.close();
break;
}
else{
outWriter.write("reulst is :" + new StringBuffer(str).reverse().toString());
outWriter.write("\r\n");
}
}
}catch(IOException e){
System.out.println("Handle client error");
}
}
public static void main(String[] args){
SimpleServer s = new SimpleServer();
s.start();
}
private int port = 3000;
private boolean runFlag = true;
}