-
Notifications
You must be signed in to change notification settings - Fork 1
/
PersonB.java
103 lines (84 loc) · 3.02 KB
/
PersonB.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
public class PersonB extends Frame implements Runnable, ActionListener{
TextField textField;
TextArea textArea;
Button sendButton;
Socket socket;
DataInputStream dataInputStream;
DataOutputStream dataOutputStream;
Thread chatThread;
// Constructor
PersonB(){
textArea = new TextArea();
textArea.setBounds(50, 50, 450, 450);
textField = new TextField();
textField.setBounds(50, 520, 200, 40);
sendButton = new Button("send");
sendButton.setBounds(260, 520, 100, 40);
// actionlistener interface is used to create listener for the send button
sendButton.addActionListener(this);
try {
// implementing the client sockets for communication
socket = new Socket("localhost", 10000);
// implementing the dataStreams for data transmission
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream = new DataOutputStream(socket.getOutputStream());
} catch (IOException e) {
// exception statement
}
// add all components to the fram
add(textArea);
add(textField);
add(sendButton);
// created thread for the listener
chatThread = new Thread(this);
chatThread.setDaemon(true);
chatThread.start();
// userinterface
setSize(600,600);
setTitle("PersonB");
setLayout(null);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent ae){
// generating the transmission data in the textfield
String message = textField.getText();
// display the generated text in the textArea
textArea.append("PersonB: " + message+"\n");
// empty the textfield after the message transmission occured
textField.setText("");
// send the genetated message
try {
// writeUTF() method is used to write the message into the outputStream
dataOutputStream.writeUTF(message);
// flush() method will send the message immediately, without storing it in the buffer
dataOutputStream.flush();
} catch (IOException e) {
// exception statement
}
}
// method for running the thread
@Override
public void run(){
// checking for the receiving messages
while(true){
try {
// receive and read the message from the personB using read() method
String message = dataInputStream.readUTF();
// display the received text in the textArea
textArea.append("PersonA: " + message+"\n");
} catch (IOException e) {
}
}
}
public static void main(String[] args){
new PersonB();
}
}