Java Reference
In-Depth Information
<html><head><title>Chat Server Test</title></head>
<body>
<form target="main" method="post"
action="http://localhost:8080/"
enctype="text/plain">
<table>
<tr><td>Nickname:</td><td><input name="nick" /></td></tr>
<tr><td>Text:</td><td><input size="80" name="text" /></td></tr>
</table>
<input value="Submit Text" type="submit" />
</form>
</body>
</html>
However, the main idea is to use J2ME devices as clients for the chat server. Listings 6.4 and 6.5
contain the MIDP and PDAP versions of the chat client. Again, the main task is performed in the
transmit method in both cases, which sends a new string to the server and updates the display of the
client with the messages received from the server.
The transfer method is called from two points in the program:
• From the event handler when the user requests to send some text. In that case, the string to be
submitted to the server is given as a parameter.
• Periodically from a refresh task every four seconds with null as a parameter, in order to keep
the message display of the client updated.
The transfer method takes the string to be sent to the server as parameter, or null if the local list of
messages should only be updated from the server without sending a new message. Depending on this
parameter, a HTTP connection is opened in READ or READ_WRITE mode. The URI is constructed
from the hostname that was queried by the user interface and stored in the host variable and the start
parameter, denoting from which message number the server should start sending. The count variable
is initialized with the value -1 , so for the first request, the server will send back the 10 most recent
messages. The count variable is updated later in this method from the response of the server. Because
IO exceptions might be thrown during the connection, you include the whole method in a try - catch
block. The Boolean return value indicates whether the transfer was performed successfully:
boolean transfer (String submit) { // if null, just read
try {
HttpConnection connection = (HttpConnection) Connector.open
(host + "/?start="+count,
submit != null ? Connector.READ_WRITE : Connector.READ);
If submit is not null , a corresponding writer is obtained from the HTTP connection, and the method
is set to POST . Then, the message stored in the submit variable is submitted as content of the request:
Writer writer = null;
if (submit != null) {
connection.setRequestMethod (HttpConnection.POST);
writer = new OutputStreamWriter
(((StreamConnection) connection).openOutputStream());
writer.write ("nick="+nick + "\r\n");
writer.write ("text="+submit+"\r\n");
writer.close();
}
Now you open a reader in order to read the new messages submitted with the reply from the server:
 
 
Search WWH ::




Custom Search