连接到服务器时接收和使用控制台输入

时间:2016-09-20 16:45:46

标签: java string sockets client java.util.scanner

我既使用了阅读器对象又使用了扫描程序,但是当这个客户端连接到一个简单的套接字服务器并且它们都在运行时,我无法从控制台中的用户那里获取输入并将其传递给服务器。按Enter键只是跳过一行,scan.nextLine()似乎没有捕获任何东西,或者在将变量传递给输出流光时出现问题。

import java.io.*;
import java.net.*;
import java.util.Scanner;
public class Client {
public static void main(String[] args) {
    Socket socket = null;  
    DataOutputStream outputStream = null;
    BufferedReader reader = null;

    Scanner scan = new Scanner(System.in);
    String message;

    String host = "macbook";
    int port = 9999;

    //attempts to connect to given host and port
    try {
        socket = new Socket(host, port);
        outputStream = new DataOutputStream(socket.getOutputStream());
        reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));           
    } catch (UnknownHostException e) {
        System.err.println("Don't know about host: " + host +".");
    } catch (IOException e) {
        System.err.println("Couldn't get I/O for the connection to: " + host+".");
        e.printStackTrace();
    }

    // if everything has been initialized then write some data
    if (socket != null && outputStream != null && reader != null) {
        try {
            message=scan.nextLine();

            outputStream.writeBytes(message);    
            String responseLine;
            while ((responseLine = reader.readLine()) != null) {
                System.out.println("Server: " + responseLine);
                if (responseLine.indexOf("Ok") != -1) {
                  break;
                }
            }
            //closes client once communication with server has ended
            outputStream.close();
            reader.close();
            socket.close();   
        } catch (UnknownHostException e) {
            System.err.println("Trying to connect to unknown host: " + e);
        } catch (IOException e) {
            System.err.println("IOException:  " + e);
        }
    }
}           
}

0 个答案:

没有答案