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

发表于:2007-06-22来源:作者:点击数: 标签:
import java .io.*; importjava.net.*; /** *Demonstrateshowtowritea Java Server * *@seeClientSocketDemo ***/ publicclassServerSocketDemo { publicstaticvoidmain(Stringargs[])throwsException { //setupserveronport6000 ServerSocketss=newServerSo

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


/**
 * Demonstrates how to write a Java Server
 *
 * @see ClientSocketDemo
 ***/

public class ServerSocketDemo
{
    public static void main(String args[]) throws Exception
    {
        // setup server on port 6000
        ServerSocket ss = new ServerSocket(6000);
        System.out.println(">> Waiting for client connection...");
        
        // This can be placed in a while loop to serve multiple clients
        Socket s = ss.aclearcase/" target="_blank" >ccept();
        
        // Print input
        System.out.println(">> Connection received, reading data...");
        BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
        PrintWriter pw = new PrintWriter(s.getOutputStream());
        
        System.out.println(br.readLine());
        
        System.out.println(">> Sending message back");
        pw.println("Good Bye!");
        pw.flush();
        
        // close sockets
        pw.close();
        br.close();
        ss.close();
        
        System.out.println(">> Done!");
    }
}

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