我想在java中編寫一個簡單的http服務器。這裏是我到目前爲止的代碼:Java套接字寫入然後從套接字讀取
服務器:
import java.net.*;
import java.io.*;
import java.util.*;
import java.util.regex.*;
public class Server
{
static final int PORT = 8080;
final String REQUEST_FORMAT = "^GET (.*?) HTTP/1.1$";
final Socket client;
public Server(Socket s)
{
client = s;
}
public void run()
{
try
(Scanner in = new Scanner(new InputStreamReader(client.getInputStream()));
PrintWriter out = new PrintWriter(client.getOutputStream(),true);)
{
String request = in.findInLine(Pattern.compile(REQUEST_FORMAT));
System.out.println(request);
out.write("HTTP/1.1 200 OK");
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
public static void main(String []args)
{
try
(
ServerSocket server = new ServerSocket(PORT);
Socket client = server.accept();
)
{
Server s = new Server(client);
s.run();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}
客戶:
import java.net.*;
import java.io.*;
import java.util.*;
public class Client
{
final int PORT = 8080;
String data = "GET /home/index.html HTTP/1.1";
public Client()
{
try
(Socket socket = new Socket("127.0.0.1",PORT);
PrintWriter out = new PrintWriter(socket.getOutputStream(),true);
Scanner in = new Scanner(new InputStreamReader(socket.getInputStream()));)
{
out.print(data);
String header1 = in.next();
System.out.println("header="+header1);
int status = in.nextInt();
System.out.println("status="+status);
String message = in.next();
System.out.println("message="+message);
}
catch(Exception ex)
{
}
}
public static void main(String []args)
{
Client c = new Client();
}
}
目前客戶端只是寫了一個樣本請求到服務器,服務器寫入的樣本響應頭。但是,服務器似乎在讀取請求之後無限期地等待客戶端輸入,而無需繼續發送響應。請幫助解決這個問題。在
String request = in.findInLine(Pattern.compile(REQUEST_FORMAT));
但是,如果我在最後寫新行,這不是錯的。據我所知,HTTP GET請求最後沒有換行符? – PPGoodMan 2015-02-23 17:51:37
@PP好心人你錯了。不要做出無證據的猜測。 – EJP 2015-02-23 18:01:38
您是否試圖實現一個簡單的套接字服務器和套接字客戶端?它有用嗎?從那裏你可以做出改進,使它看起來像一個Http套接字服務器 – alainlompo 2015-02-23 18:43:35