Java Chat Code
The Java object hierarchy includes many classes that handle many sorts of data types and data connections. The "Socket" and "ServerSocket" classes represent simple connections a Java program can make to another program through the ports of a computer. Through these objects, a Java program can receive data or messages, such as text, from a remote computer. So, for example, a simple chat client written in Java would run Socket and ServerSocket objects to send and receive messages.
-
Chat Server and ServerSocket
-
At its most basic, a Java chat server will use a ServerSocket object to listen for a connection. The "accept" method forces the program to wait until a connection is established. This method returns a "Socket" object representing the accepted connection. As illustrated in the following code example, the chat program will always listen for an incoming connection on a particular port and return the connection socket:
import java.net.ServerSocket;
import java.net.Socket;
import java.io.BufferedReader;
import java.io.InputStreamReader;class Chat{
public static void main (String[] args) {
ServerSocket s = null;
s = new ServerSocket(9999);
Socket s = server.accept();
}
}
Receiving Messages
-
Once the connection is made, the programmer can read input from the socket. This input, the message from another chatter, will read into a "BufferedInput" object, which can then read its information into a String variable:
BufferedReader input = new BufferedReader(new InputStreamReader(
s.getInputStream()));
String message = input.readline(); -
Storing Messages
-
When receiving messages from the remote computer, it may be beneficial to store them in an array so that a multiple message isn't lost. In practice, what the programmer might do is store messages in an array with a revolving "while" loop. For each received message, the loop will store a message in the array and move to the next index, wrapping around to the first index when the array is full:
String[] messages = new String[20];
int index = 0;
message = input.readLine();while (message != null) {
messages[index] = message;
index++;
message = input.readLine();
}
Sending Messages
-
The programmer can also use socket objects to connect to a remote computer that is listening for communications. By using the socket to connect, the programmer can open an output stream to send a message to the user. She accomplishes this by using an PrintWriter object, attaching it to the socket's output stream and writing through the socket:
Socket connect = new Socket("http:\\www.computer.domain", 9999);
out = new PrintWriter(connect.getOutputStream(), true);
out.print("Sending Message...");
-