自从在课上学完了socket编程,就没接触过,当初的理解很肤浅。
本例实现一个基于控制台的http客户端和服务端。
HttpServ.java
package cn.pangython.httpserv;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
/**
* @author pangPython
* socket通信,服务器端
*/
public class HttpServ {
private ServerSocket serverSocket = null;
private Socket socket = null;
private InputStream inputStream = null;
private InputStreamReader inputStreamReader;
private BufferedReader bufferedReader;
public HttpServ(int port) throws IOException {
System.out.println("服务器启动成功!");
System.out.println("服务器正在监听"+port+"端口");
//建立服务端socket
serverSocket = new ServerSocket(port);
//监听,等待客户机连接
socket = serverSocket.accept();
//获取socket的输入流
inputStream = socket.getInputStream();
//输入流读取器
inputStreamReader = new InputStreamReader(inputStream);
//缓冲读取
bufferedReader = new BufferedReader(inputStreamReader);
String line;
System.out.println("这是客户端发来的信息:");
//遍历打印
while ((line = bufferedReader.readLine())!=null) {
System.out.println(line);
}
System.out.println("完成一次交互");
}
public static void main(String[] args) {
try {
new HttpServ(9090);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
HttpClient.java
package cn.pangpython.httpclient;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
/**
* @author pangPython
* socket通信客户端
*/
public class HttpClient {
private Socket socket = null;
private OutputStream outputStream = null;
private PrintWriter printWriter;
public HttpClient(String host,int port) throws UnknownHostException, IOException {
//进行socket连接
socket = new Socket(host, port);
//获取输出流
outputStream = socket.getOutputStream();
//输出流打印器
printWriter = new PrintWriter(outputStream);
//写出要发送的信息
printWriter.write("本消息是客户端发来的信息...");
//将信息刷入socket
printWriter.flush();
//关闭释放资源
printWriter.close();
outputStream.close();
socket.close();
}
public static void main(String[] args) {
try {
new HttpClient("127.0.0.1", 9090);
} catch (IOException e) {
e.printStackTrace();
}
}
}
当然实现一个http服务器并不是那么容易,要循环监听客户端,要多线程,要解析协议头信息等。