2

我编写了一个基本程序来演示客户端服务器交互。连接正在建立,但无法从流中获取数据。它抛出一个异常,说明连接重置

服务器

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class SocketServer {

    private ServerSocket serverSocket;
    private int port;

    public SocketServer(int port) {
        this.port = port;
    }

    public void start() throws IOException {
        System.out.println("Starting the socket server at port:" + port);
        serverSocket = new ServerSocket(port);

        System.out.println("Waiting for clients...");
        Socket client = serverSocket.accept();

        sendWelcomeMessage(client);
    }

    private void sendWelcomeMessage(Socket client) throws IOException {
        BufferedWriter writer = new BufferedWriter(new                        OutputStreamWriter(client.getOutputStream()));
        writer.write("Hello. You are connected to a Simple Socket Server. What is your   name?");
        writer.flush();
    }

    /**
    * Creates a SocketServer object and starts the server.
    *
    * @param args
    */
    public static void main(String[] args) {
        // Setting a default port number.
        int portNumber = 9990;

        try {
            // initializing the Socket Server
            SocketServer socketServer = new SocketServer(portNumber);
            socketServer.start();

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

客户

 import java.io.BufferedReader;
 import java.io.BufferedWriter;
 import java.io.IOException;
 import java.io.InputStreamReader;
  import java.io.OutputStreamWriter;
 import java.net.Socket;
 import java.net.UnknownHostException;

public class SocketClient {

private String hostname;
private int port;
Socket socketClient;

public SocketClient(String hostname, int port){
    this.hostname = hostname;
    this.port = port;
}

public void connect() throws UnknownHostException, IOException{
    System.out.println("Attempting to connect to "+hostname+":"+port);
    socketClient = new Socket(hostname,port);
    System.out.println("Connection Established");
}

public void readResponse() throws IOException{
    String userInput;
    BufferedReader stdIn = new BufferedReader(new InputStreamReader(socketClient.getInputStream()));

    System.out.println("Response from server:");
    while ((userInput = stdIn.readLine()) != null) {
        System.out.println(userInput);
    }
}

public static void main(String arg[]){
    //Creating a SocketClient object
    SocketClient client = new SocketClient ("localhost",9990);
    try {
        //trying to establish connection to the server
        client.connect();
        //if successful, read response from server
        client.readResponse();

    } catch (UnknownHostException e) {
        System.err.println("Host unknown. Cannot establish connection");
    } catch (IOException e) {
        System.err.println("Cannot establish connection. Server may not be up."+e.getMessage());
e.printStackTrace();
    }
}
}

##OUTPUT##

Attempting to connect to localhost:9990
Connection Established
Response from server:
Hello. You are connected to a Simple Socket Server. What is your name?
       java.net.SocketException: Connection reset
    at java.net.SocketInputStream.read(Unknown Source)
    at sun.nio.cs.StreamDecoder.readBytes(Unknown Source)
    at sun.nio.cs.StreamDecoder.implRead(Unknown Source)
    at sun.nio.cs.StreamDecoder.read(Unknown Source)
    at java.io.InputStreamReader.read(Unknown Source)
    at java.io.BufferedReader.fill(Unknown Source)
    at java.io.BufferedReader.readLine(Unknown Source)
    at java.io.BufferedReader.readLine(Unknown Source)
    at SocketClient.readResponse(SocketClient.java:31)
    at SocketClient.main(SocketClient.java:45)
4

2 回答 2

2

当前的实现至少有一个问题。您利用readLine()来获取数据 - 但是readLine()这样做:

读取一行文本。一行被认为是由换行符 ('\n')、回车符 ('\r') 或紧跟换行符的回车符中的任何一个终止的。

您发出数据的程序不使用换行符来终止“消息”:

writer.write("Hello. You are connected to a Simple Socket Server. What is your name?");
writer.flush();

要终止消息,请添加一个换行符:

writer.write("Hello. You are connected to a Simple Socket Server. What is your name?");
writer.write("\n");              // shown separately for clarity
writer.flush();
于 2013-05-12T06:04:12.203 回答
0

我实际上也为此苦苦挣扎了一段时间,但我相信我找到了更准确的答案,并认为我应该分享它。原始示例从不关闭BufferedWriter. 所以只需添加writer.close()after writer.flush(),就像这样:

writer.write("Hello. You are connected to a Simple Socket Server. What is your name?");
writer.flush();
writer.close();

因为它从未关闭,所以输出永远不会为空,因此while循环永远不会失败。

于 2013-07-15T16:58:35.547 回答