import java.io.*;
import java.net.*;public class SockServerExam 
{
int portnum = 5555;
public static void main(String args[])
{
new SockServerExam().work();
}
void work()
{
try
{

ServerSocket server_socket=new ServerSocket(portnum);
System.out.println("listen on "+portnum);
while(true)
{
Socket socket = server_socket.accept();
System.out.println("New connection accepted " +
   socket.getInetAddress() +
   ":" + socket.getPort());
RequestHandler rh = new RequestHandler(socket);
Thread th = new Thread(rh);
th.start();

}
}
// catch(InterruptedException e)
// {
// e.printStackTrace();
// }
catch(IOException eio)
{
eio.printStackTrace();
}

}

}
class RequestHandler implements Runnable
{
Socket conn;
InputStream input;
    OutputStream output;
    BufferedReader br;
    byte[] buf;
public RequestHandler(Socket s)
{
try
{
conn=s;
this.input = conn.getInputStream();
this.output = conn.getOutputStream();
buf = new byte[256];
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void run()
{
int receive_count=0;
int readcount = 1;
try
{
while(readcount>0)
{
readcount=input.read(buf);
System.out.println("received num:"+readcount);
if(readcount>0)
receive_count+=readcount;
}
System.out.println("connection accepted " +
   conn.getInetAddress() +
   ":" + conn.getPort()+ " received bytes:" + receive_count);
input.close();
output.close();
conn.close();
}
catch(Exception e)
{
e.printStackTrace();
} }
}

解决方案 »

  1.   


    import java.nio.*;
    import java.nio.channels.*;
    import java.net.*;
    import java.io.*;
    import java.nio.channels.spi.*;
    import java.nio.charset.*;
    import java.lang.*;
    public class Client
    {
        public SocketChannel client = null;
        public InetSocketAddress isa = null;
        public RecvThread rt = null;    public Client()
        {
        }
        
    public void makeConnection()
        {
    int result = 0;
    try
    {

    client = SocketChannel.open();
    isa = new InetSocketAddress("dell1",4900);
    client.connect(isa);
    client.configureBlocking(false);
    receiveMessage();    
    }
    catch(UnknownHostException e)
    {
    e.printStackTrace();
    }
    catch(IOException e)
    {
    e.printStackTrace();
    }
    while ((result = sendMessage()) != -1)
    {
    } try
    {
    client.close();
    System.exit(0);
    }
    catch(IOException e)
    {
    e.printStackTrace();
    }
        }
        
    public int sendMessage()
        {
    System.out.println("Inside SendMessage");
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    String msg = null;
    ByteBuffer bytebuf = ByteBuffer.allocate(1024);
    int nBytes = 0;
    try
    {
    msg = in.readLine();
    System.out.println("msg is "+msg);
    bytebuf = ByteBuffer.wrap(msg.getBytes());
    nBytes = client.write(bytebuf);
    System.out.println("nBytes is "+nBytes);
    if (msg.equals("quit") || msg.equals("shutdown")) {
    System.out.println("time to stop the client");
    interruptThread();
    try
    {
    Thread.sleep(5000);
    }
    catch(Exception e)
    {
    e.printStackTrace();
    }
    client.close();
    return -1;
    }
        
    }
            catch(IOException e)
    {
    e.printStackTrace();
    }
    System.out.println("Wrote "+nBytes +" bytes to the server");
    return nBytes;
        }    public void receiveMessage()
        {
    rt = new RecvThread("Receive THread",client);
    rt.start();    }    public void interruptThread()
        {
    rt.val = false;
        }    public static void main(String args[])
        {
    Client cl = new Client();
    cl.makeConnection();
        }    public class RecvThread extends Thread
        {
    public SocketChannel sc = null;
    public boolean val = true;

    public RecvThread(String str,SocketChannel client)
    {
    super(str);
    sc = client;
    }

    public void run() { System.out.println("Inside receivemsg");
    int nBytes = 0;
    ByteBuffer buf = ByteBuffer.allocate(2048);
    try
    {
    while (val)
    {
    while ( (nBytes = nBytes = client.read(buf)) > 0){
    buf.flip();
    Charset charset = Charset.forName("us-ascii");
    CharsetDecoder decoder = charset.newDecoder();
    CharBuffer charBuffer = decoder.decode(buf);
    String result = charBuffer.toString();
    System.out.println(result);
    buf.flip();

    }
    }

    }
    catch(IOException e)
    {
    e.printStackTrace();

    }
                 }
        }
    }
      

  2.   

    看看这个吧,比楼上的简单的一个客户端import java.net.*;
    import java.io.*;
    class Whois
    {
    public static void main(String args[]) throws Exception
    {
    int c;
    Socket s = new Socket("internic.net", 43);
    InputStream in = s.getInputStream();
    OutputStream out = s.getOutputStream();
    String str = www.csdn.net
    byte buf[] = str.getBytes();
    out.write(buf);
    while ((c = in.read()) != -1)
    {
    System.out.print((char) c);
    }
    s.close();
    }
    }
      

  3.   

    给一个简单的Whois客户机
      public final static int DEFAULT_PORT = 43;
      public final static String DEFAULT_HOST = "whois.internic.net";  public static void main(String[] args){
      InetAddress server;   try{
      server = InetAddress.getByName(DEFAULT_HOST);
      }
      catch(UnknownHostException e){
      System.err.println("Error: Could not locate default host " + DEFAULT_HOST);
      System.err.println("Check to make sure you're connected to the Internet and that DNS is funtioning");
      System.err.println("Usage: java WhiosClient host port ");
      return;
      }   int port  = DEFAULT_PORT;
      try{
      Socket theSocket = new Socket(server,port);
      Writer out = new OutputStreamWriter(theSocket.getOutputStream(),"8859_1");
      for(int i = 0;i < args.length;i++) out.write(args[i] + " ");
      out.write("\r\n");
      out.flush();
      InputStream raw = theSocket.getInputStream();
      InputStream in = new BufferedInputStream(raw);
      int c;
      while((c = in.read()) != -1) System.out.write(c);
      }
      catch(IOException e){
      System.err.println(e);
      }
      }
      

  4.   

    朋友,thinking in java里的socket实例讲的非常好,而且很经典,建议去看看
    并且实践一下,不会让你失望
    good luck
      

  5.   

    learning java(o'reilly) 上也有呀。
    这个好像基本上是java的书都有
      

  6.   

    import java.net.*;
    import java.io.*;
    public class DaytimeClient
       {
         public static void main(String[] args)
           {
             String hostname;
             if(args.length>0)
               {
                 hostname=args[0];
                }
             else
               {
                 hostname="www.sina.com";
                }
             try
              {
                Socket theSocket=new Socket(hostname,13);
                InputStream timeStream=theSocket.getInputStream();
                StringBuffer time=new StringBuffer();
                int c;
                while((c=timeStream.read())!=-1)time.append((char)c);
                String timeString=time.toString().trim();
                System.out.println("It is "+timeString +" at "+hostname);
              }
            catch(UnknownHostException e)
              {
                System.err.println(e);
               }
            catch(IOException e)
               {
                 System.err.println(e);
                }
            }
         }
      

  7.   

    三个类,可用来作ftp服务器用的一个实例
    import java.io.*;
    import java.net.*;public class FTPServer{
    ThreadGroup group;
    FTPServer(){
    group=new ThreadGroup("FTPThreads");
    }
    protected void finalize(){
    group.stop();
    }
    public static void main(String[] args){
    ServerSocket server;
    Socket socket;
    FTPServer ftp=new FTPServer();
    try{
    server=new ServerSocket(1999);
    System.out.println("Listening on port: 1999");
    }catch(IOException e){
    System.out.println("e");
    return;
    }
    while(true){
    try{
    socket=server.accept();
    System.out.println("New user form"+socket.getInetAddress().toString());
    (new FTPServerThread(ftp.group,ftp,socket)).start();
    }catch(IOException e){
    System.out.println(e);
    return;
    }
    }
    }
    }
    __________________________________________
    import java.io.*;
    import java.net.*;class FTPServerThread extends Thread{
    FTPServer ftp;
    Socket socket;
    DataInputStream in;
    PrintStream out;
    String line;
    FileList fl;
    public FTPServerThread(ThreadGroup group,FTPServer ftp,Socket socket){
    super(group,"FTPThread");
    this.ftp=ftp;
    this.socket=socket;
    fl=new FileList("d:/ftp");
    }
    public void run(){
    try{
    in=new DataInputStream(socket.getInputStream());
    out=new PrintStream(socket.getOutputStream());
    while(true){
    line=in.readLine();
    if(line.trim().equals("ls")){
    fl.Display(out);
    }else if(line.trim().equals("quit")){
    break;
    }else if(line.substring(0,2).equals("cd")){
    fl.ChDir(line.substring(2).trim(),out);
    }else if(line.substring(0,3).equals("get")){
    fl.put(line.substring(3).trim(),out);
    }else{
    out.println("Invalid command");
    }
    }
    in.close();
    out.close();
    System.out.println("User "+socket.getInetAddress().toString()+" leaved");
    socket.close();
    }
    catch(IOException e){
    System.out.println(e);
    }
    }
    }
    _________________________________________
    import java.io.*;
    import java.net.*;class FileList{
    File f;
    FileList(String dir){
    f=new File(dir);
    }
    public void ChDir(String dir,PrintStream out){
    if(dir.equals("..")){
    if(f.getParent()!=null){
    f=new File(f.getParent());
    out.println("Current directory: "+f.getPath());
    }
    else{
    out.println("Already root directory!");
    }
    }
    else{
    File g=new File(f,dir);
    if(g.exists()&&g.isDirectory()){
    f=g;
    out.println("Current directory: "+f.getPath());
    }
    else{
    out.println("No such directory!");
    }
    }
    }
    public void Display(PrintStream out){
    String[] st=f.list();
    File g;
    out.println(st.length);
    for(int i=0;i<st.length;i++){
    g=new File(f,st[i]);
    if(g.isFile()){
    out.println(format(st[i],20,false)+format(String.valueOf(g.length()),10,true));
    }
    else{
    out.println(format(st[i],20,false)+format("<DIR>",10,true));
    }
    }
    }
    private String format(String s,int len,boolean pre){
    StringBuffer buf=new StringBuffer(s);
    while(buf.length()<len){
    if(pre){
    buf.insert(0," ");
    }else{
    buf.append(" ");
    }
    }
    return(new String(buf));
    }
    public void put(String fn,PrintStream out){
    File g=new File(f,fn);
    if(g.exists()&&g.isFile()){
    try{
    FileInputStream fin=new FileInputStream(g);
    int len=(int)g.length();
    byte[] content=new byte[len];
    out.println(len);
    fin.read(content,0,len);
    fin.close();
    out.write(content,0,len);
    }
    catch(IOException e){}
    }
    else{
    out.print(-1);
    out.println("No such file!");
    }
    }
    }
    _________________________________________
    import java.io.*;
    import java.net.*;public class FTPClient{
    public static void main(String[] args){
    Socket socket;
    DataInputStream in;
    PrintStream out;
    String line;
    DataInputStream din=new DataInputStream(System.in);
    //if(args.length!=1){
    // System.out.println("Usage: java FTPClient <hostname>");
    // return;
    //}
    try{
    socket=new Socket("192.168.28.82",1999);
    in=new DataInputStream(socket.getInputStream());
    out=new PrintStream(socket.getOutputStream());
    while(true){
    System.out.println();
    System.out.print(":");
    line=din.readLine();
    if(line.equals(" "))continue;
    out.println(line);
    if(line.trim().equals("quit"))break;
    else if(line.trim().equals("ls")){
    int num=Integer.parseInt(in.readLine());
    for(int i=0;i<num;i++){
    line=in.readLine();
    System.out.println(line);
    }
    System.out.println("Total: "+num+" Items");
    }else if(line.trim().substring(0,3).equals("get")){
    int len=Integer.parseInt(in.readLine());
    if(len<0){
    line=in.readLine();
    System.out.println(line);
    }
    else{
    FileOutputStream fout=new FileOutputStream("d:/down/"+line.substring(3).trim());
    byte[] content=new byte[len];
    in.read(content,0,len);
    fout.write(content,0,len);
    fout.close();
    System.out.println(len+" bytes received");
    }
    }
    else{
    line=in.readLine();
    System.out.println(line);
    }
    }
    in.close();
    out.close();
    socket.close();
    }
    catch(IOException e){
    System.out.println(e);
    }
    }
    }


      

  8.   

    服务端的
    import java.net.*;
    import java.io.*;public class SimpleServer{
      public static void main(String args[]){
          ServerSockct s=null;
          Socket s1;
          String sendString="hello world";
    int slength=sendString.length();
    OutputStream slout;
    DataOutputStream dos;
    try{
       s=new ServerSocket(5432);
    }
    catch(IOException e){}
    while(true){
      try{
      s1=s.accept();
    slout=s1.getOutputStream();
    dos=new DataOutputStream(slout);
    dos.writeUTF(sendString);
    dos.close();
    slout.close();
    s1.close();
    }
    catch(IOException e){}
    }
    }
    }
    客户端的
    import java.net.*;
    import java.io.*;
    public class SimpleClient{
      public static void main(String args[])throws IOException{
    int c;
    Socket s1;
    InputStream s1In;
    DataInputSteam dis;
    s1=new Socket("subbert",5432);
    s1In=s1.getInputStream();
    dis=new DataInputStream(s1In);
    String st=new String(dis.readUTF());
    System.out.println(st);
    dis.close();
    s1In.close();
    s1.close();
    }
    }