-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMultiThreadChatClient.java
79 lines (76 loc) · 2.48 KB
/
MultiThreadChatClient.java
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
import java.io.*;
import java.net.*;
public class MultiThreadChatClient implements Runnable
{
private static Socket clientSocket = null;// The client socket
private static PrintStream os = null;// The client socket
private static DataInputStream is = null; // The input stream
private static BufferedReader inputLine = null;
private static boolean closed = false;
public static void main(String[] args)
{
int portNumber = 2222; // The default port.
String host = "localhost";// The default host.
if (args.length < 2)
System.out.println("Usage: java MultiThreadChatClient <host> <portNumber>\n"+ "Now using host=" + host + ", portNumber=" + portNumber);
else
{
host = args[0];
portNumber = Integer.valueOf(args[1]).intValue();
}
//Open a socket on a given host and port. Open input and output streams.
try
{
clientSocket = new Socket(host, portNumber);
inputLine = new BufferedReader(new InputStreamReader(System.in));
os=new PrintStream(clientSocket.getOutputStream());
is=new DataInputStream(clientSocket.getInputStream());
}
catch (UnknownHostException e)
{
System.err.println("Don't know about host " + host);
}
catch (IOException e)
{
System.err.println("Couldn't get I/O for the connection to the host "+ host);
}
// If everything has been initialized then we want to write some data to the socket we have opened a connection to on the port portNumber.
if (clientSocket != null && os != null && is != null)
{
try
{
new Thread(new MultiThreadChatClient()).start();// Create a thread to read from the server.
while (!closed)
{
os.println(inputLine.readLine().trim());
}
// Close the output stream, close the input stream, close the socket.
os.close();
is.close();
clientSocket.close();
}
catch (IOException e)
{
System.err.println("IOException: " + e);
}
}
}
//Create a thread to read from the server.
public void run() {
//Keep on reading from the socket till we receive "Bye" from the server. Once we received that then we want to break.
String responseLine;
try {
while ((responseLine = is.readLine()) != null)
{
System.out.println(responseLine);
if (responseLine.indexOf("*** Bye") != -1)
break;
}
closed = true;
}
catch (IOException e)
{
System.err.println("IOException: " + e);
}
}
}