簡體   English   中英

Java套接字。 服務器 - 客戶端通信

[英]Java Sockets. Server-Client communication

我正在嘗試將客戶端與gui連接到一個沒有gui的服務器。 正在進行連接,但我無法看到這兩個應用之間的任何消息。 (我應該在客戶端獲取SERVER,在服務器中獲取客戶端)

客戶端連接代碼:

@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類中定義。定義為“受保護的BufferedReader輸入;受保護的PrintWriter輸出;”)

另外,服務器代碼:

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!");
    }
}

連接似乎沒問題,所以我不知道什么是錯的。 任何幫助,將不勝感激。

PS:我也在服務器上嘗試過PrintWriter,並嘗試在流語句中嘗試catch,問題依然存在。

你正在使用readLine() ,它需要一個換行符。 要么為要發送的消息添加\\n ,要么不使用readLine()

[求助]正如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");

}

多謝你們!

將這段代碼與過去使用套接字編寫的一些代碼進行比較后,我注意到你正在使用output.write(string)input.readline() - 這些不能很好地混合, readline()需要一個換行符並且write不會給出一。

println()替換write() println()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM