-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChatClient.java
More file actions
79 lines (70 loc) · 2.68 KB
/
Copy pathChatClient.java
File metadata and controls
79 lines (70 loc) · 2.68 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/**
* ChatClient.java
*
* This program implements a simple multithreaded chat client. It connects to the
* server (assumed to be localhost on port 7654) and starts two threads:
* one for listening for data sent from the server, and another that waits
* for the user to type something in that will be sent to the server.
* Anything sent to the server is broadcast to all clients.
*
* The ChatClient uses a ClientListener whose code is in a separate file.
* The ClientListener runs in a separate thread, receives messages form the server,
* and displays them on the screen.
*
* Data received is sent to the output screen, so it is possible that as
* a user is typing in information a message from the server will be
* inserted.
*
*/
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.Scanner;
public class ChatClient {
/**
* main method.
* @params not used.
*/
public static void main(String[] args) {
try {
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter a Username: ");
String userName = keyboard.nextLine();
String hostname = "localhost";
int port = 7654;
//System.out.println("Connecting to server on port " + port);
Socket connectionSock = new Socket(hostname, port);
DataOutputStream serverOutput = new DataOutputStream(connectionSock.getOutputStream());
System.out.println("Connection made.\n");
// Start a thread to listen and display data sent by the server
ClientListener listener = new ClientListener(connectionSock);
Thread theThread = new Thread(listener);
theThread.start();
boolean firstPass = true;
// Read input from the keyboard and send it to everyone else.
// The only way to quit is to hit control-c, but a quit command
// could easily be added.
while (true) {
if (firstPass) {
serverOutput.writeBytes(userName + "\n");
firstPass = false;
}
String data = userName + ": " + keyboard.nextLine();
serverOutput.writeBytes(data + "\n");
// If user types goodbye chat ends
String[] checkForGoodbye = data.split(":",2);
if (checkForGoodbye[1].length() > 7
&& (checkForGoodbye[1].substring(0, 8).equals(" goodbye")
|| checkForGoodbye[1].substring(0,8).equals(" Goodbye")
|| checkForGoodbye[1].substring(0,8).equals(" GOODBYE"))) {
System.out.println("** EXITING APPLICATION **");
System.exit(0);
}
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
} // MtClient