Java核心代码例程之:ClientSocketDemo.java

1/5/2008来源:Java教程人气:6186


import java.io.*;
import java.net.*;


/**
 * Demonstrates how to write a Java client
 *
 * @see ServerSocketDemo
 ***/
public class ClientSocketDemo
{
    public static void main(String args[]) throws Exception
    {
        Socket s = new Socket("localhost", 6000);
        PRintWriter pw = new PrintWriter(s.getOutputStream());
        BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
        
        System.out.println(">> Connection with server established");
        pw.println("Hello World!");
        pw.flush();
        
        // Print input
        System.out.println(">> Reading output from server");
        System.out.print(br.readLine());
        System.out.println("
>> Done!");
        
        // close sockets
        pw.close();
        br.close();
        s.close();
    }
}