用socket寫的http服務器只能從客戶端讀取一次資料,后面就不能讀取了,但是服務器和客戶端之間還是有tcp連接,并且可以向客戶端回傳資料

服務器端的代碼:
public class Server {
private static final Integer port=7777;
public static void main(String[] args) {
ServerSocket Serversocket;
try {
System.out.println("Server start...");
Serversocket=new ServerSocket(port);//創建Socket,監聽客戶端請求
//服務器一直處于監聽狀態
while (true){
Socket socket=Serversocket.accept();//服務器一直處于監聽狀態,并且在此處等待,當有客戶端的訊息到達時,才繼續向下執行
System.out.println("build a new tcp link with the client,the addressis: "+socket.getInetAddress()+":"+socket.getPort());
//并發處理客戶端HTTP請求
service(socket);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void service(Socket socket){
new Thread(new Runnable() {
@Override
public void run() {
InputStream inSocket;
try {
inSocket=socket.getInputStream();//獲取HTTP請求頭
int size=inSocket.available();
byte[] buffer=new byte[size];
inSocket.read(buffer);
String request=new String(buffer);
//System.out.println("----------------------------------------------------------\nClientBrowser:\n"+request+"\n----------------------------------------------------------------");
String contentType="application/json";
if(request.length()>0){
System.out.println(request);
}
//將回應發送給客戶端
//System.out.println(flag);
String responseFirstLine="HTTP/1.1 200 OK\r\n";
String responseHead="Content-Type:"+contentType+"\r\n";
OutputStream outSocket=socket.getOutputStream();
//System.out.println("----------------------------------------------------------\nServerResponse:\n"+request+"\n----------------------------------------------------------------");
outSocket.write(responseFirstLine.getBytes());
outSocket.write(responseHead.getBytes());
outSocket.write("\r\n".getBytes());
//回應報文頭部結束,接下來寫入內容
outSocket.write("{\"name\":\"gyy\",".getBytes());
outSocket.write("\"words:\":\"i love you\"}".getBytes());
outSocket.flush();
//inSocket.close();
outSocket.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
}
uj5u.com熱心網友回復:
我單步進去看的時候,又能夠讀取到訊息,但是直接運行就不可以,大佬們,我該怎么做啊uj5u.com熱心網友回復:
read判斷一下回傳值把轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/59552.html
標籤:網絡通信
