我正在尝试自学Java网络编程。
这是尝试实现请求 - 响应:
服务器:
public class SimpleServer1 {
public static void main(String[] args) throws IOException
{
ServerSocket sSock = new ServerSocket(8888);
System.out.println("++++++++++++ started server ++++++++++++");
System.out.println("++++++++++++ waiting for connections ++++++++++++");
Socket curConn = sSock.accept();
// get output stream to dispatch to client
OutputStream os = curConn.getOutputStream();
PrintWriter pw = new PrintWriter(os);
// get input stream to read from the client
InputStreamReader isr = new InputStreamReader(curConn.getInputStream());
BufferedReader br = new BufferedReader(isr);
pw.write(" ++++++++++++ HandShake from Server ++++++++++++");
pw.flush();
while(true)
{
System.out.println("in server loop :");
String curClientInput = br.readLine();
if(curClientInput.equals("Bye"))
{
break;
}
pw.write("I am your Server : " + curClientInput);
pw.flush();
}
System.out.println("++++++++++++ shutting down server ++++++++++++");
br.close();
isr.close();
pw.close();
os.close();
}
}
客户端:
public class SimpleClient1 {
public static void main(String[] args) throws UnknownHostException, IOException
{
Socket sock = new Socket("localhost", 8888);
System.out.println(" ++++ Connecting to server ++++");
InputStreamReader isr = new InputStreamReader(sock.getInputStream());
BufferedReader br = new BufferedReader(isr);
PrintWriter out = new PrintWriter(sock.getOutputStream());
System.out.println(" ++++ connected to server ++++");
while(true)
{
System.out.println("Entered client loop :");
// reading response from server
String response = br.readLine();
System.out.println("Server says : " + response);
// dispatching to server
out.write("Hey you server !!!");
out.flush();
if(response.equalsIgnoreCase("bye"))
{
break;
}
}
out.close();
br.close();
isr.close();
}
}
当我在这里运行这些是我所看到的:
Server:
++++++++++++ started server ++++++++++++
++++++++++++ waiting for connections ++++++++++++
in server loop :
Client:
++++ Connecting to server ++++
Entered client loop :
我无法弄清楚这里出了什么问题。客户端和服务器卡在br.readLine();
它们是否陷入僵局?
答案 0 :(得分:0)
br.readLine():它读取一行文字。从文档:“读取一行文本。一行被认为是由任何一个换行符('\ n'),一个回车符('\ r')或一个回车符后跟一个换行符终止。“
http://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html
在服务器中,最后写'\ n'。