客户端/服务器程序:连接重置

时间:2013-05-12 05:56:20

标签: java sockets io

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

服务器

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)

2 个答案:

答案 0 :(得分: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();

答案 1 :(得分:0)

我实际上已经和它搏斗了一段时间,但我相信我找到了一个更准确的答案,并认为我应该分享它。原始示例永远不会关闭BufferedWriter。因此,只需在writer.close()之后添加writer.flush(),就像这样:

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

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