Created
April 14, 2021 13:50
-
-
Save ishanExtreme/c4e7a0dc8f113422f90ade34a2d34d6e to your computer and use it in GitHub Desktop.
Client
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.Console; | |
import java.io.IOException; | |
import java.net.InetAddress; | |
import java.net.Socket; | |
import java.net.UnknownHostException; | |
/** | |
* Main Class for Client Side | |
*/ | |
public class Client { | |
// ex-> localhost | |
private String hostname; | |
private int port; | |
private String userName; | |
/** | |
* Default Constructor | |
*/ | |
public Client() { | |
this.hostname = "localhost"; | |
this.port = 3000; | |
} | |
/** | |
* Parametrized Constructor | |
* | |
* @param hostname: hostname of the server | |
* @param port: port server connected to | |
*/ | |
public Client(String hostname, int port) { | |
this.hostname = hostname; | |
this.port = port; | |
} | |
/** | |
* Initialize the client socket | |
*/ | |
public void init() { | |
try { | |
// gives the IP address of the host | |
InetAddress address = InetAddress.getByName(hostname); | |
// socket constructor of type (InetAdress, portnumber) | |
Socket socket = new Socket(address, port); | |
System.out.println("Connected to the chat server"); | |
// seperate threads for reading and writing msgs | |
new ReadThread(socket, this).start(); | |
new WriteThread(socket, this).start(); | |
} catch (UnknownHostException ex) { | |
System.out.println("Server not found: " + ex.getMessage()); | |
} catch (IOException ex) { | |
System.out.println("I/O Error: " + ex.getMessage()); | |
} | |
} | |
/** | |
* Setter Method to set userName field | |
* | |
* @param userName | |
*/ | |
void setUserName(String userName) { | |
this.userName = userName; | |
} | |
/** | |
* Getter method to get value of field userName | |
* | |
* @return: userName | |
*/ | |
String getUserName() { | |
return this.userName; | |
} | |
public static void main(String[] args) { | |
Console console = System.console(); | |
String hostname = console.readLine("\nEnter hostname:"); | |
int port = Integer.parseInt(console.readLine("\nEnter port:")); | |
Client client = new Client(hostname, port); | |
client.init(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment