-
Notifications
You must be signed in to change notification settings - Fork 0
/
Client.java
89 lines (88 loc) · 2.92 KB
/
Client.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
80
81
82
83
84
85
86
87
88
89
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.Scanner;
public class Client {
Socket socket;
String username;
BufferedWriter bufferedWriter;
BufferedReader bufferedReader;
public Client(Socket socket,String username){
try{
this.socket = socket;
this.username = username;
bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
bufferedWriter.write(username);
bufferedWriter.newLine();
bufferedWriter.flush();
}catch(IOException e){
closeEverything(socket,bufferedReader,bufferedWriter);
}
}
// Helper Functions
public void sendMessage(){
while (!socket.isConnected()) {
Scanner in = new Scanner(System.in);
String messageToSend = in.nextLine();
try{
bufferedWriter.write(messageToSend);
bufferedWriter.newLine();
bufferedWriter.flush();
}catch(IOException e)
{
closeEverything(socket, bufferedReader, bufferedWriter);
in.close();
break;
}
}
}
// Listening continously for messages
public void ListenForMessages(){
Runnable MyThread = ()->{
try{
String message = bufferedReader.readLine();
System.out.println(message);
}catch(IOException e){
closeEverything(socket, bufferedReader, bufferedWriter);
}
};
Thread thread = new Thread(MyThread);
thread.start();
}
public void closeEverything(Socket socket,BufferedReader bufferedReader,BufferedWriter bufferedWriter){
try{
if(socket != null)
{
socket.close();
}
if(bufferedReader != null)
{
bufferedReader.close();
}
if(bufferedWriter != null)
{
bufferedWriter.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
public static void main(String[] args) {
try{
Socket socket = new Socket("localhost",1999);
Scanner in = new Scanner(System.in);
System.out.println("Enter your name : ");
String username = in.nextLine();
Client client = new Client(socket, username);
client.sendMessage();
client.ListenForMessages();
in.close();
}catch(IOException e){
System.out.println("ERROR : Connection cannot be established");
}
}
}