Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.DataOutputStream;
- import java.io.BufferedInputStream;
- import java.io.DataInputStream;
- import java.io.IOException;
- import java.net.Socket;
- import java.util.Scanner;
- import static java.lang.System.exit;
- //Thread class to handle input -- receiving data from server
- class ClientInputThread implements Runnable {
- //Instance variables
- private Socket socket;
- private Thread t;
- //Constructor.
- ClientInputThread(Socket s) {
- this.socket = s;
- }
- public void run() {
- //Set up connection variables
- DataInputStream input = null;
- try {
- input = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
- } catch (IOException e) {
- System.err.println(e);
- exit(1);
- }
- //Program loop. Echo text to the console. Loop ends when main thread kills this thread
- String text = "a";
- while (!text.equals("") && !t.isInterrupted()) {
- try {
- text = input.readUTF();
- System.out.println(text);
- } catch (IOException e) {
- }
- }
- try {
- input.close();
- this.socket.close();
- } catch (IOException e) {
- System.err.println(e);
- exit(1);
- }
- }
- public void start() {
- if(this.t == null) {
- t = new Thread(this);
- t.start();
- }
- }
- public void kill() {
- t.interrupt();
- }
- }
- public class Client {
- public static void main(String[] args) {
- //Set up connection variables
- String hostName = args[0];
- int portNumber = Integer.parseInt(args[1]);
- Socket socket = null;
- Scanner console = new Scanner(System.in);
- DataOutputStream output = null;
- //Establish connection to server
- try {
- socket = new Socket(hostName, portNumber);
- } catch (IOException e) {
- System.err.println(e);
- exit(1);
- }
- //Get output stream
- try {
- output = new DataOutputStream(socket.getOutputStream());
- } catch (IOException e) {
- System.err.println(e);
- exit(1);
- }
- //Create a separate thread to handle receiving data from server.
- ClientInputThread in = new ClientInputThread(socket);
- in.start();
- //Program loop. Send commands to server.
- String line = "a", userName = null, password = null;
- while (!line.equals("/logout")) {
- try {
- line = console.nextLine();
- output.writeUTF(line);
- } catch (IOException e) {
- System.err.println(e);
- exit(1);
- }
- }
- //Close connection.
- try {
- console.close();
- output.close();
- socket.close();
- in.kill();
- } catch (IOException e) {
- System.err.println(e);
- exit(1);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement