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

发表于:2007-06-22来源:作者:点击数: 标签:
import java .io.*; importjava.net.*; /** *Demonstrateshowtowritea Java client * *@seeServerSocketDemo ***/ publicclassClientSocketDemo { publicstaticvoidmain(Stringargs[])throwsException { Sockets=newSocket(localhost,6000); PrintWriterpw=n

   
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();
    }
}

原文转自:http://www.ltesting.net