package com.cyyun.xc.command.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import javax.net.ServerSocketFactory;
public class testendpoint {
protected volatile boolean running = false;
/**
* Server socket acceptor thread.
*/
protected ServerSocket serverSocket = null;
protected ServerSocketFactory serverSocketFactory = null;
public void start() throws Exception {
running = true;
// 获得serverSocketFactory
serverSocketFactory = ServerSocketFactory.getDefault();
// 获得serverSocket,监听8080端口
serverSocket = serverSocketFactory.createServerSocket(8888);
// 建立监听线程
Thread acceptorThread = new Thread(new Acceptor(), "-Acceptor-");
acceptorThread.start();
}
// 处理socket
protected boolean processSocket(Socket socket) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
}
return true;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
testendpoint ts = new testendpoint();
try {
System.out.println("Server start");
ts.start();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// 监听类,不断循环
protected class Acceptor implements Runnable {
/**
* The background thread that listens for incoming TCP/IP connections
* and hands them off to an appropriate processor.
*/
public void run() {
// Loop until we receive a shutdown command
while (running) {
// Loop if endpoint is paused
// Accept the next incoming connection from the server socket
try {
Socket socket = serverSocket.accept();
// Hand this socket off to an appropriate processor
if (!processSocket(socket)) {
// Close socket right away
try {
socket.close();
} catch (IOException e) {
// Ignore
}
}
} catch (IOException x) {
} catch (Throwable t) {
}
// The processor will recycle itself when it finishes
}
}
}
}
Server start
GET / HTTP/1.1
Host: localhost:8888
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; rv:31.0) Gecko/20100101 Firefox/31.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Connection: keep-alive
POST /aer HTTP/1.1
Content-Length: 1189
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Host: 127.0.0.1:8888
Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.3.5 (java 1.5)
POST / HTTP/1.1
Content-Length: 1189
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Host: 127.0.0.1:8888
Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.3.5 (java 1.5)
POST / HTTP/1.1
Content-Length: 10
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Host: 127.0.0.1:8888
Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.3.5 (java 1.5)