Socket编程
传统的socket网络编程是同步或者是阻塞的I/O,服务器每次只能处理一个请求,其他请求阻塞等待
public class TimeServer {
public static void main(String[] args) {
int port = 8088;//端口号
ServerSocket server = null;
try {
server = new ServerSocket(port);
System.out.println("The time server is start in port:"+port);
Socket socket = null;
while(true){
//监听客户端,客户端向服务端发送请求,接收
socket = server.accept();
//当监听到客户端请求,服务端启动一个线程,处理客户端相关业务
new Thread(new TimeServerHandler(socket)).start();
}
} catch (IOException e) {
e.printStackTrace();
}finally{
if(server != null){
System.out.println("the server close");
try {
server.close();
} catch (IOException e) {
e.printStackTrace();
}
server = null;
}
}
}
}
------------
public class TimeServerHandler implements Runnable{
private Socket socket;
public TimeServerHandler(Socket socket){
this.socket = socket;
}
@Override
public void run() {
BufferedReader in = null;
PrintWriter out = null;
try {
in = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
out = new PrintWriter(this.socket.getOutputStream());
String currentTime = null;
String body = null;
while(true){
//读取客户端信息
body = in.readLine();
if(body == null)
break;
System.out.println("the time server receive order:"+body);
currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body) ?
new java.util.Date(System.currentTimeMillis()).toString() : "BAD ORDER";
out.println(currentTime);
}
} catch (Exception e) {
if(in != null){
try {
in.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
if(out != null){
out.close();
}
if(socket != null){
try {
socket.close();
} catch (IOException e1) {
e1.printStackTrace();
}
this.socket = null;
}
}
}
}
--------------
public class TimeClient {
public static void main(String[] args) {
int port = 8088;//端口
BufferedReader in = null;
PrintWriter out = null;
Socket socket = null;
try {
//根据ip地址和端口连接服务器;
socket = new Socket("127.0.0.1", 8088);
//使用IO流读取或写入信息
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream());
out.write("QUERY TIME ORDER");
System.out.println("send order 2 server succeed");
String resp = in.readLine();
System.out.println("NOW IS:"+resp);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(out != null){
out.close();
}
if(in != null){
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
socket = null;
}
}
}
}