当前,我正在尝试将多个消息从客户端发送到服务器,并在服务器上回显它们,但是不知何故,直到我按CTRL + Z(D)并按Enter键,消息才到达服务器。 只要用户不输入“ quit”,我的循环就一直运行,但是尽管如此,我还是将消息写到OutputStream并刷新了它,但消息没有显示在服务器端,好像我的客户端仍在读取输入。
(纯粹出于学习原因,我现在不想使用BufferedReaders或Threads。)
如果有人能告诉我我的错误/错误在哪里,那会很好。 另请阅读javadocs,但仍然找不到我的错误。
Client.java
public class Client {
//class members
private String msg = null;
private Scanner scn = null;
public Client(String ip, int port) throws IOException {
//Connect to Server
try(Socket socket = new Socket(ip,port))
{
//Initialize class members
scn = new Scanner(System.in); //Init Scanner
msg="";
System.out.println("Enter message:");
//Write to Socket
OutputStream out = socket.getOutputStream();
while(!msg.equals("quit"))
{
msg=scn.nextLine();
out.write(msg.getBytes(), 0, msg.length());
out.flush();
}
}
catch (IOException ex)
{
System.err.println(ex);
}
}
Server.java
public class Server {
//class members
private String msg = null;
public Server(int port) throws IOException {
//Setup ServerSocket.
ServerSocket server = new ServerSocket(port);
System.out.println("SERVER: Launched service.");
//Accept incoming connection requests.
while(true) {
try(Socket connection = server.accept())
{
System.out.println("SERVER: Client connection accepted.");
//Read Input
StringBuilder line = new StringBuilder();
InputStream in = connection.getInputStream();
for(int c=in.read(); c!=-1; c=in.read())
{
line.append((char) c);
}
System.out.println(line);
}
catch (IOException ex)
{
System.out.println("SERVER: Client disconnected!");
}
}
}
此致, y
答案 0 :(得分:0)
read()
返回-1之前,您的服务器不打印任何内容。read()
在流的末尾返回-1。您的程序按设计运行。