如何将数据发送到客户端类之外的服务器

时间:2017-08-19 07:08:10

标签: java sockets client

我正在编写服务器客户端程序。它就像一个简单的控制台聊天室。我使用服务器线程来处理多个客户端。如果我将Scanner放在客户端构造函数中,它会很好。(这部分已注释)但是,我想将请求用户输入的Scanner部分移动到main。我得到socket close error。我不知道问题是什么。如何使用send函数在main中发送数据?

客户端:

public class GameClient {
private Socket socket;
private String serverIP;
private OutputStreamWriter writer;
private BufferedReader reader;

public GameClient(String host){
    this.serverIP = host;

    try{
        //Connect to server
        socket = new Socket(InetAddress.getByName(serverIP), 1234);
        writer = new OutputStreamWriter(this.socket.getOutputStream(), "UTF-8");
        reader = new BufferedReader(new InputStreamReader(this.socket.getInputStream(), "UTF-8"));
        //Start a new thread for reading from server
        new Thread(new GameClientReader(socket)).start();

        Scanner scanner = new Scanner(System.in);
        System.out.println("Write something: ");
        String str = "";
//          while((str = scanner.nextLine()) != null){
//              writer.write(str);
//              writer.write('\n');
//              writer.flush();
//              System.out.println("Write something: ");
//          }

    }catch(IOException e){
        System.out.println("Client failed to connect!");
        e.printStackTrace();
    }finally{
        try {
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


public void send(JSONObject json){
    try{
        String message = json.toJSONString();
        writer.write(message);
        writer.write('\n');
        writer.flush();
    }catch(IOException e){
        e.printStackTrace();
    }
}

public void send(String msg){
    try {
        writer.write(msg);
        writer.flush();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public static void main(String args[]){
    GameClient client = new GameClient("127.0.0.1");

    Scanner scanner = new Scanner(System.in);
    System.out.println("Write something: ");
    String str = "";
    while((str = scanner.nextLine()) != null){
        client.send(str);
        System.out.println("Write something: ");
    }

}
}

1 个答案:

答案 0 :(得分:0)

关闭Socket构建函数的finally块中的GameClient,然后调用方法send,该方法调用使用writer.write(msg);实例的Socket