如何在java

时间:2016-08-23 04:53:12

标签: java multithreading serversocket

我有两个不同的类Client.java和Server.java。 Client.java有两个线程,一个是使用scanner类从用户那里获取输入并将数据发送到服务器,一个线程从服务器读取并在屏幕上打印。如果服务器发送特定关键字如“shutdown”,我想终止运行用户输入命令。 这是客户端代码

package client;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;

public class DirClient extends Thread {
Socket client;
DataOutputStream out;
Scanner input;
boolean clientState = true;

DirClient(String serverName, int port) {
    try {
        client = new Socket(serverName, port);
        out = new DataOutputStream(client.getOutputStream());
        System.out.println("Connected to : " + client.getRemoteSocketAddress());

    } catch (Exception e) {
        // TODO: handle exception
    }
}

void close() {
    clientState = false;
    input.close();
    try {
        client.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

void sendToServer() {
    String operation;
    try {
        input = new Scanner(System.in);

        ReadFromServer objRFS = new ReadFromServer(client, this);
        objRFS.start(); // start thread to read data from server
        while (clientState) { // loop to read user input and send to server
            operation = input.nextLine();
            if (operation.equalsIgnoreCase("exit")) {
                break; // if operation is exit then stop recieving user
                        // input
            }
            out.writeUTF(operation);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    finally {
        close();
    }
}

public static void main(String[] args) {
    String serverName = args[0];
    int port = Integer.parseInt(args[1]);

    DirClient objDirClient = new DirClient(serverName, port);
    objDirClient.sendToServer();
}

}

//与服务器通信以获取服务器响应的类

class ReadFromServer extends Thread {

Socket client = null;
DataInputStream in = null;
DirClient objDirClient;

ReadFromServer(Socket client, DirClient dirClient) {

    try {
        this.client = client;
        objDirClient = dirClient;
        in = new DataInputStream(client.getInputStream());
    } catch (Exception e) {
    }
}

public void run() {
    String response;

    try {
        while (true) {
            response = in.readUTF();

            if (response.equalsIgnoreCase("shutdown")) {
                objDirClient.close();
                break;
            }
            System.out.println("Response :\n" + response);

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

}

}

如果客户端从服务器读取关键字,我从主线程调用了close函数。由于主线程的控制是来自用户的输入所以这不会终止,直到用户输入内容。

0 个答案:

没有答案