-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChatClient.java
More file actions
54 lines (43 loc) · 1.38 KB
/
ChatClient.java
File metadata and controls
54 lines (43 loc) · 1.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
/*
This is the chat client program.
The class takes a hostname and a port as arguments in its constructor and
creates a socket to connect to the ChatServer.
Type 'bye' to terminate the program.
*/
public class ChatClient {
private String hostname;
private int port;
private String userName;
public ChatClient(String hostname, int port) {
this.hostname = hostname;
this.port = port;
}
public void execute() {
try {
Socket socket = new Socket(hostname, port);
System.out.println("Connected to the chat server");
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());
}
}
void setUserName(String userName) {
this.userName = userName;
}
String getUserName() {
return this.userName;
}
public static void main(String[] args) {
if (args.length < 2) return;
String hostname = args[0];
int port = Integer.parseInt(args[1]);
ChatClient client = new ChatClient(hostname, port);
client.execute();
}
}