Java Reference
In-Depth Information
Example 5•8: GenericClient.java
package com.davidflanagan.examples.net;
import java.io.*;
import java.net.*;
/**
* This program connects to a server at a specified host and port.
* It reads text from the console and sends it to the server.
* It reads text from the server and sends it to the console.
**/
public class GenericClient {
public static void main(String[] args) throws IOException {
try {
// Check the number of arguments
if (args.length != 2)
throw new IllegalArgumentException("Wrong number of args");
// Parse the host and port specifications
String host = args[0];
int port = Integer.parseInt(args[1]);
// Connect to the specified host and port
Socket s = new Socket(host, port);
// Set up streams for reading from and writing to the server.
// The from_server stream is final for use in the inner class below
final Reader from_server=new InputStreamReader(s.getInputStream());
PrintWriter to_server = new PrintWriter(s.getOutputStream());
// Set up streams for reading from and writing to the console
// The to_user stream is final for use in the anonymous class below
BufferedReader from_user =
new BufferedReader(new InputStreamReader(System.in));
// Pass true for auto-flush on println()
final PrintWriter to_user = new PrintWriter(System.out, true);
// Tell the user that we've connected
to_user.println("Connected to " + s.getInetAddress() +
":" + s.getPort());
// Create a thread that gets output from the server and displays
// it to the user. We use a separate thread for this so that we
// can receive asynchronous output
Thread t = new Thread() {
public void run() {
char[] buffer = new char[1024];
int chars_read;
try {
// Read characters until the stream closes
while((chars_read = from_server.read(buffer)) != -1) {
// Loop through the array of characters, and
// print them out, converting all \n characters
// to the local platform's line terminator.
// This could be more efficient, but it is probably
// faster than the network is, which is good enough
for(int i = 0; i < chars_read; i++) {
if (buffer[i] == '\n') to_user.println();
else to_user.print(buffer[i]);
}
Search WWH ::




Custom Search