Java套接字客户端应用程序

时间:2014-02-04 00:18:12

标签: java sockets

我试图找出java套接字如何工作,我在这里有这个代码。如果我通过输入流输入值,但是如果我将值作为字符串发送,则此功能将不会停止,它会循环并且不会停止。

public void sendToServer(String username, String shopid, String number){
String hostname = "localhost";
int port = 6789;



    Socket clientSocket = null;  
    DataOutputStream os = null;
    BufferedReader is = null;



    try {
        clientSocket = new Socket(hostname, port);
        os = new DataOutputStream(clientSocket.getOutputStream());
        is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
    } catch (UnknownHostException e) {
        System.err.println("Don't know about host: " + hostname);
    } catch (IOException e) {
        System.err.println("Couldn't get I/O for the connection to: " + hostname);
    }



if (clientSocket == null || os == null || is == null) {
    System.err.println( "Something is wrong. One variable is null." );
    return;
}

try {
    while ( true ) {
    System.out.print( "Enter an integer (0 to stop connection, -1 to stop server): " );
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String keyboardInput = br.readLine();
    os.writeBytes( keyboardInput + "\n" );

    int n = Integer.parseInt( keyboardInput );
    if ( n == 0 || n == -1 ) {
        break;
    }

    String responseLine = is.readLine();
    System.out.println("Server returns its square as: " + responseLine);
    }



    os.close();
    is.close();
    clientSocket.close();   
} catch (UnknownHostException e) {
    System.err.println("Trying to connect to unknown host: " + e);
} catch (IOException e) {
    System.err.println("IOException:  " + e);
}


 }

这是处理输入的服务器部分:

 public void run() {
     String line;
try {
    boolean serverStop = false;

        while (true) {
            line = is.readLine();
    System.out.println( "Received " + line + " from Connection " + id + "." );
            int n = Integer.parseInt(line);
    if ( n == -1 ) {
        serverStop = true;
        break;
    }
    if ( n == 0 ) break;
            os.println("" + n*n ); 
        }

    System.out.println( "Connection " + id + " closed." );
        is.close();
        os.close();
        clientSocket.close();

    if ( serverStop ) server.stopServer();
} catch (IOException e) {
    System.out.println(e);
}
}

谢谢。

0 个答案:

没有答案