Java套接字。服务器-客户端通信

3
我正在尝试连接一个带有图形用户界面的客户端和一个没有图形用户界面的服务器。连接已经建立,但是我无法在这两个应用程序之间看到任何消息。 (我应该在客户端中看到“SERVER HERE”,在服务器中看到“CLIENT HERE”)
客户端连接代码:
@Override
public void ClientRunning(){
    try {
       connectToServer();
        setStreams();
        ClientRun();

    }catch(EOFException oefException){
        showMessage("\n Client terminated the connection\n");
    }catch(IOException ioException){
        ioException.printStackTrace();
    }finally{
        close();
    }
}



public void connectToServer() throws IOException{
    showMessage("Attempting Connection... \n");
    connection = new Socket(InetAddress.getByName(serverIP),6789);
    showMessage("Connected to: "+ connection.getInetAddress().getHostName());
}


public void setStreams() throws IOException{
   output = new PrintWriter(connection.getOutputStream(),true);
   output.flush();
   input= new BufferedReader(new InputStreamReader(connection.getInputStream()));

    showMessage("\n Streams are now set. \n");
}

public void close(){
    showMessage("\n closing...");
    try{
      output.close();
      input.close();
      connection.close();

    }catch(IOException ioException){
        ioException.printStackTrace();
    }
}
public void showMessage(final String text){
    SwingUtilities.invokeLater(new Runnable(){
        public void run(){
            cwindow.append(text);
        }
    });
}

public void sendMessage(String message){
    output.write("CLIENT - "+message);
    output.flush();
    showMessage("\nCLIENT - "+message);
}

private void ClientRun() throws IOException{
    String message="CLIENT HERE!";
    sendMessage(message);
    do{
        try{
            message=input.readLine();
            showMessage("\n"+message);
        }catch(EOFException eofException){
                showMessage("\n Server ended the connection!");
    }

    }while(message!="EXIT");
    }

在GUI类中定义了输入和输出,该客户端类是其扩展。定义为“protected BufferedReader input; protected PrintWriter output;”。
此外,还有服务器代码:
public class ServerClass {


private ServerSocket server;
private Socket connection;
private BufferedReader input;
private BufferedWriter output;


public void startServer(){
    try{
        server=new ServerSocket(6789,100);
        while(true){
            try{
                waitForConnection();
                setStreams();
                ServerRunning();
            }catch(EOFException eofException){
                showMessage("\n Server ended the connection!");

            }finally{
            close();

        }
        }

    }catch(IOException ioException){
        ioException.printStackTrace();
    }
}

private void waitForConnection() throws IOException{
    showMessage("Waiting for someone to connect... \n");
    connection=server.accept();
    showMessage("Now connected to "+ connection.getInetAddress().getHostName());
}

private void setStreams() throws IOException{
   output = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
   output.flush();
   input= new BufferedReader(new InputStreamReader(connection.getInputStream()));

    showMessage("\n Streams are now set. \n");
}
public void ServerRunning() throws IOException{
    String message="SERVER HERE!";
    sendMessage(message);
    do{
        try{

            message=input.readLine();
            showMessage("\n"+message);
        }catch(EOFException eofException){
                showMessage("\n Server ended the connection!");
    }

    }while(message!="EXIT");

  }
private void close(){
    showMessage("\n Closing connections... \n");
    try{
        output.close();
        input.close();
        connection.close();

}catch(IOException ioException){
    ioException.printStackTrace();
}
}
private void showMessage(String text){
    System.out.println(text);
}

private void sendMessage(String message){
    try{
       output.write("SERVER - "+message);
        output.flush();
        showMessage(message);
    }catch(IOException ioException){
        System.out.println("\n ERROR!");
    }
}

连接似乎没问题,所以我不知道出了什么问题。任何帮助都将不胜感激。
附注:我在服务器中也尝试使用PrintWriter,并在流语句中尝试了try catch,但问题仍然存在。

setStreams() 中的 flush() 是无意义的。因为你还没有写任何东西,所以没有需要刷新的内容。你的服务器结构不支持多个客户端。 - user207421
3个回答

2

您正在使用readLine()方法,该方法需要一个换行符。请在发送的信息中添加\n或不要使用readLine()方法。


1
[SOLVED] 正如TedTrippin和Alfie提到的,readline()搞乱了我的代码。在每个消息中添加"\n"后,一切似乎都运行得很顺利!我还将客户端代码中的printwriter更改为bufferwritter,并在sendMessage中添加了try-catch函数,因为由于某些原因,printwritter似乎也会引起一些问题。 无论如何,一切都已经设置好了!谢谢大家!
更新后的客户端代码:
private void ClientRun() throws IOException{
    String message="CLIENT HERE! \n"; <----added \n here.
    sendMessage(message);
    do{
        try{
            message=input.readLine();
            showMessage("\n"+message);
        }catch(EOFException eofException){
                showMessage("\n Server ended the connection!");
    }

    }while(message!="EXIT");
    }

public void sendMessage(String message){
    try{                                 <-----added try-catch statement
       output.write("CLIENT - "+message+"\n"); <----adding "\n" here is super userful, instead of having to add \n in each message.
        output.flush();
        showMessage(message);
    }catch(IOException ioException){
        System.out.println("\n ERROR!");
    }
}

protected BufferedReader input;
protected BufferedWriter output; <----changed printwriter to BufferWriter

更新的服务器代码:
public void ServerRunning() throws IOException{
    String message="SERVER HERE! \n";    <--- added \n here as well.
    sendMessage(message);
    do{
        try{

            message=input.readLine();
            showMessage("\n"+message);
        }catch(EOFException eofException){
                showMessage("\n Server ended the connection!");
    }

    }while(message!="EXIT");

}

谢谢大家!


0

在将此代码与我以前使用套接字编写的一些代码进行比较后,我注意到您正在使用output.write(string)input.readline() - 这两者不兼容,readline()需要一个换行符,而write则没有。

请用println()替换write()


项目在术语上规定不使用线程,这使得它变得有点棘手......但还是谢谢回复。 - b10z
@b10z 哦,好的,你可以尝试不使用另一个线程来查看是否存在问题。 - Alfie
但是你是分别运行服务器和客户端的,对吧? - TedTrippin
当然,它们是完全不同的项目。一切都设置正确,因为我收到了带有IP地址的连接消息,但仅此而已。连接没有关闭,但是我没有得到“SERVER HERE”和“CLIENT HERE”消息,就像我应该得到的那样... - b10z

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接