I am doing my homework dedicated to the chat program. It has two interfaces: one for the server, the second for the client. The program flow is as follows:
- The server starts a connection on a specific port
- The client starts and tries to connect to the server
- If everything is ok, they start chatting
- One of the terminals of type "TERMINATE" will be completed.
This program was created from the book Deitel & Deitel Java How To Program 6e . The example has only two elements for each interface: displayArea (JTextArea) for displaying messages and input (JTextField) for entering messages.
Clicking Enterwill send the message to the other side.
The following is a snippet of Server.java code. It performs some repetitive actions in an infinite loop.
public void runServer() {
SwingUtilities.invokeLater(new Runnable() {
public void run()
{
try {
String portNum = txtPort.getText();
server = new ServerSocket(Integer.parseInt(portNum), 100);
InetAddress ip = InetAddress.getLocalHost();
txtServerIP.setText(ip.getHostAddress());
while (true) {
try {
waitForConnection();
getStreams();
processConnection();
}
catch (EOFException eofException) {
System.err.println("Client terminated the connection.");
}
finally {
closeConnection();
++counter;
}
}
}
catch (IOException ioException) {
ioException.printStackTrace();
}
}
});
}
It works well with source code. I decided to add some GUI interfaces to the interfaces and added the application window using Eclipse Luna 4.4.1. I added an input for the IP address and port number. Then I added the "Open Connection" button for the server GUI and another "Connect to Server" button for the client GUI.
Server.java, , " ". , . Client.java " " . Client , .
, Server - while ( true ). , , . , - .
?
public void runServer() {
SwingUtilities.invokeLater(new Runnable() {...
public void runServer() {
SwingUtilities.invokeLater(new Thread() {...
.
ServerGUI.java @http://pastebin.com/pVRi6EfC
ClientGUI.java @http://pastebin.com/HfftM159
:
Server.java @http://pastebin.com/6Q5Z00gb
Client.java @http://pastebin.com/uCGFGknf