computer 版 (精华区)

发信人: arbo (arbo), 信区: program
标  题: java笔记11
发信站: 听涛站 (2001年09月17日10:52:25 星期一), 站内信件

发信人: airforce1 (五湖废人), 信区: Java
标  题: java笔记11
发信站: BBS 水木清华站 (Mon Apr  3 10:59:30 2000)
开始讲hot的networking le
基本概念有了吧,什么叫tcp/ip, socket, 不说了
x=new ServerSocket("8080");
socket y=x.accept();
y.getInputStream();
y.getOutputStream();
//这是server端
client:
x=new socket("...",8080);
x.getOutputStream(.)
x.getOutputStream();
协议可以自己来定义,也可以按照rfc的网络协议来看
两种协议tcp and Udp, 有连接与无连接。
tcp要握手,udp是不用,但是发出的包是包含了目的地的地址信息
udp可靠性没有tcp高,但是不是说tcp更好
看写关于socket的资料吧,在写java网络程序前,不然不会
写出稳定,安全的程序 ((有一本书不错,推荐"internet 编程“紫封面的)
一些例子
www, 的
//  index.html in c:\root
import java.io.*;
import java.net.*;
import java.util.*;
class WWWUtil{
        final static String version="1.0";
        final static String mime_text_plain="text/plain";
        final static String mime_text_html="text/html";
        final static String mime_image_gif="image/gif";
        final static String mime_image_jpg="image/jpg";
        final static String mime_app_os="application/octet-stream";
        final static String CRLF="\r\n";
        public static byte toBytes(String s)[]{
                byte b[]=new byte[s.length()];
                s.getBytes(0,b.length,b,0);
                return b;
        }
        public static byte byteArrayConcat(byte a[],byte b[])[] {
                byte ret[]=new byte[a.length+b.length];
                System.arraycopy(a,0,ret,0,a.length);
                System.arraycopy(b,0,ret,a.length,b.length);
                return ret;
        }
        public static byte mimeHeader(String ct,int size)[]{
                return mimeHeader(200,"OK",ct,size);
        }
        public static byte mimeHeader(int code,String msg,String ct,int size
)[]{
                Date d=new Date();
                return toBytes("HTTP/1.0 "+code+" "+msg+CRLF+
                                                "Date:"+d.toGMTString()+CRLF
+
                                                "Server:Java/"+version+CRLF+

                                                "Content-type:"+ct+CRLF+
                                                (size>0?"Content-length:"+si
ze+CCRLF:" ")+CRLF);
        }
        public static byte error(int code,String msg,String fname)[]{
                String ret="<body>"+CRLF+"<h1>"+code+" "+msg+"</h1>"+CRLF;
                if (fname!=null)
                        ret+="Error when fetching URL:"+fname+CRLF;
                ret+="</body>"+CRLF;
                byte tmp[]=mimeHeader(code,msg,mime_text_html,0);
                System.out.println(tmp+ret);
                return byteArrayConcat(tmp,toBytes(ret));
        }
        public static String mimeTypeString(String filename){
                String ct;
                if (filename.endsWith(".html")||filename.endsWith(".htm"))
                        ct=mime_text_html;
                else if (filename.endsWith(".class"))
                        ct=mime_app_os;
                else if (filename.endsWith(".gif"))
                        ct=mime_image_gif;
                else if (filename.endsWith(".jpg"))
                        ct=mime_image_jpg;
                else
                        ct=mime_text_plain;
                return ct;
        }
}
class HTTPlog{
        public static void error(String entry)
                throws IOException{
                OutputStream f=new FileOutputStream("c:/http.log");
                byte log[]=new byte[2048];
                System.out.println("Error:"+entry);
                log=WWWUtil.byteArrayConcat(WWWUtil.toBytes("Error"),WWWUtil
.toBBytes(entry));
                f.write(log);
                f.close();
        }
        public static void request(String request)
                throws IOException{
                OutputStream f=new FileOutputStream("c:/http.log");
                byte log[]=new byte[2048];
                System.out.println(request);
                log=WWWUtil.toBytes(request);
                f.write(log);
                f.close();
        }
}
class thttp{
        public static final int port=80;
        final static String docRoot="c:/root";
        final static String indexfile="default.htm";
        final static int buffer_size=2048;
        final static int RT_GET=1;
        final static int RT_UNSUP=2;
        final static int RT_END=4;
        private static void handleUnsup(String request,OutputStream out)
                throws Exception{
                HTTPlog.error("Unsupported Request:"+request);
        }
        private static void handleGet(String request,OutputStream out)
                throws Exception{
                int fsp=request.indexOf(' ');
                int nsp=request.indexOf(' ',fsp+1);
                String filename=request.substring(fsp+1,nsp);
                filename=docRoot+filename+(filename.endsWith("/")?indexfile:
"");
                //System.out.println(filename);
                try{
                        File f=new File(filename);
                        if(!f.exists()){
                                System.out.println("File not found");
                                out.write(WWWUtil.error(404,"Not Found",file
namee));
                                return;
                        }
                        if(!f.canRead()){
                                out.write(WWWUtil.error(404,"Permission Deni
ed",,filename));
                                return;
                        }
                        InputStream input=new FileInputStream(f);
                        String mime_header=WWWUtil.mimeTypeString(filename);

                        int n=input.available();
                        out.write(WWWUtil.mimeHeader(mime_header,n));
                        byte buf[]=new byte[buffer_size];
                        while ((n=input.read(buf))>=0){
                                out.write(buf,0,n);
                        }
                        input.close();
                }catch(IOException e){
                        HTTPlog.error("Exception"+e);
                }
        }
        private static String getRawRequest(InputStream in)
                throws Exception{
                try{
                        byte buf[]=new byte[buffer_size];
                        boolean gotCR=false;
                        int pos=0;
                        int c;
                        while((c=in.read())!=-1){
                                switch(c){
                                case '\r':
                                        break;
                                case '\n':
                                        if (gotCR)
                                                return new String(buf,0,0,po
s);
                                        gotCR=true;
                                default:
                                        if (c!='\n') gotCR=false;
                                        buf[pos++]=(byte) c;
                                }
                        }
                }catch (IOException e){
                        HTTPlog.error("Recrieve Error");
                }
                return null;
        }
        public static void main(String args[]) throws Exception{
                ServerSocket acceptSocket=new ServerSocket(port);
                while(true){
                        String request;
                        Socket s=acceptSocket.accept();
                        InputStream input=s.getInputStream();
                        OutputStream output=s.getOutputStream();
                        int type;
                        if((request=getRawRequest(input))!=null){
                                type=request.regionMatches(true,0,"GET ",0,4
)?RTT_GET:RT_UNSUP;
                                switch(type){
                                        case RT_GET:
                                                handleGet(request,output);
                                                        break;
                                        case RT_UNSUP:
                                        default:
                                                handleUnsup(request,output);

                                                break;
                                }
                                HTTPlog.request(request);
                        }
                        input.close();
                        output.close();
                        s.close();
                }
        }
}
电子邮件的client
import java.io.*;
import java.net.*;
public class client {
    public static void main(String args[]){
       try
        {  Socket s = new Socket("202.120.127.220", 25);
          PrintStream out = new PrintStream(s.getOutputStream());
          BufferedReader in = new BufferedReader(new  InputStreamReader(s.ge
tInpputStream()));
          out.println("HELO " + "xyx");
          in.readLine();
           out.println("MAIL FROM: " + "xyx@yc.shu.edu.cn");
          in.readLine();
             out.println("RCPT TO: " + "xyx@yc.shu.edu.cn");
          in.readLine();
             out.println("DATA");
          in.readLine();
             out.println("how are 220\n");
             out.println("This is a test\n");
          in.readLine();
             out.println(".\n");
          in.readLine();
            out.println("QUIT");
          }
         catch(Exception e) {
              System.out.println("Error " + e); }
   }
}
ftp server
import java.io.*;
import java.net.*;
public class MyFtpd extends Thread
{
  public static void main(String[] args)
      {
           if(args.length != 0) {
            //  System.out.println(args[0]);
                r = args[0];}
           else{ r = "c:";}
           int i = 1;
           try
              { ServerSocket s = new ServerSocket(21);
                    for(;;)
                    { Socket incoming = s.accept();
                      new MyFtpd(incoming,i).start();
                      i++;
                    }
               }
            catch(Exception e){}
      }
       public MyFtpd(Socket income, int c)
           { incoming = income; counter = c; }
       public void run()
       {  int lng,lng1,lng2,i,ip1,ip2,ip = 1,h1;
          String a1,a2,di,str1,user="",host,dir;
          System.out.println(r);
          dir = r;
          InetAddress inet;
          InetAddress localip;
          try
            { inet = incoming.getInetAddress();
              localip = inet.getLocalHost();
              host = inet.toString();
              h1 = host.indexOf("/");
              host = host.substring(h1 + 1);
              // System.out.println(host);
              BufferedReader in
               = new BufferedReader(new InputStreamReader(incoming.getInputS
treaam()));
              PrintWriter out
               = new PrintWriter(incoming.getOutputStream(),true);
              out.println("220 MyFtp server[JAVA FTP server written by S.Tan
aka]]ready.\r");
              boolean done = false;
              while(!done)
                 {  a1 = "";
                    a2 = "";
                    String str = in.readLine();
          if(str.startsWith("RETR")){
                        out.println("150 Binary data connection");
                        str = str.substring(4);
                        str = str.trim();
                        System.out.println(str);
                        System.out.println(dir);
                        RandomAccessFile outFile = new
                        RandomAccessFile(dir+"/"+str,"r");
                        Socket t = new Socket(host,ip);
                        OutputStream out2
                           = t.getOutputStream();
                        byte bb[] = new byte[1024];
                        int amount;
                       try{
                        while((amount = outFile.read(bb)) != -1){
                              out2.write(bb, 0, amount);
                          }
                        out2.close();
                        out.println("226 transfer complete");
                        outFile.close();
                        t.close();
                       }
                        catch(IOException e){}
                  }
          if(str.startsWith("STOR")){
                        out.println("150 Binary data connection");
                        str = str.substring(4);
                        str = str.trim();
                        System.out.println(str);
                        System.out.println(dir);
                        RandomAccessFile inFile = new
                        RandomAccessFile(dir+"/"+str,"rw");
                        Socket t = new Socket(host,ip);
                        InputStream in2
                           = t.getInputStream();
                        byte bb[] = new byte[1024];
                        int amount;
                       try{
                        while((amount = in2.read(bb)) != -1){
                              inFile.write(bb, 0, amount);
                          }
                        in2.close();
                        out.println("226 transfer complete");
                        inFile.close();
                        t.close();
                       }
                        catch(IOException e){}
                  }
          if(str.startsWith("TYPE")){
                        out.println("200 type set");}
          if(str.startsWith("DELE")){
                        str = str.substring(4);
                        str = str.trim();
                        File f = new File(dir,str);
                        boolean del = f.delete();
                        out.println("250 delete command successful");}
          if(str.startsWith("CDUP")){
                        int n = dir.lastIndexOf("/");
                        dir = dir.substring(0,n);
                        out.println("250 CWD command succesful");
                                     }
          if(str.startsWith("CWD")){
                        str1 = str.substring(3);
                        dir = dir+"/"+str1.trim();
                        out.println("250 CWD command succesful");
                                     }
          if(str.startsWith("QUIT")) {
                        out.println("GOOD BYE");
                        done = true; }
          if(str.startsWith("USER")){
                        user = str.substring(4);
                        user = user.trim();
                        out.println("331 Password");}
          if(str.startsWith("PASS")) out.println("230 User "+user+" logged i
n.")
          if(str.startsWith("PWD")){
                        out.println("257 \""+dir+"\" is current directory");

            }
          if(str.startsWith("SYS"))  out.println("500 SYS not understood");
          if(str.startsWith("PORT")) {
                        out.println("200 PORT command successful");
                        lng = str.length() - 1;
                        lng2 = str.lastIndexOf(",");
                        lng1 = str.lastIndexOf(",",lng2-1);
                        for(i=lng1+1;i<lng2;i++){
                              a1 = a1 + str.charAt(i);}
                        for(i=lng2+1;i<=lng;i++){
                              a2 = a2 + str.charAt(i); }
                        ip1 = Integer.parseInt(a1);
                        ip2 =Integer.parseInt(a2);
                        ip = ip1 * 16 *16 + ip2;
                                       }
          if(str.startsWith("LIST")) {
                        try
                        {  out.println("150 ASCII data");
                           Socket t = new Socket(host,ip);
                           PrintWriter out2
                             = new PrintWriter(t.getOutputStream(),true);
                           File f = new File(dir);
                           String[] a = new String[10];
                           String d,e;
                           int i1,j1;
                           a = f.list();
                           j1 = a.length;
                           d = f.getName();
                           for(i1=0;i1<j1;i1++)
                             {   if( a[i1].indexOf(".") == -1)    // DIR
                                 { di = "d ";}
                                 else
                                 { di = "- ";}
                           out2.println(di+a[i1]);
                             }
                           t.close();
                           out.println("226 transfer complete");
                           }
                           catch(IOException e){}
                                       }
          }
          incoming.close();
        }
        catch (Exception e)
        { // System.out.println(e);
        }
     }
private Socket incoming;
private int counter;
private static String r;
}
ftp client
import java.io.*;
import java.net.*;
public class ftpc {
    public static void main(String[] args)
    {  try {
       Socket s = new Socket("202.120.127.219", 21);
          PrintStream out = new PrintStream(s.getOutputStream());
          BufferedReader in
             = new BufferedReader(new  InputStreamReader(s.getInputStream())
);
       System.out.println(in.readLine());
         out.println("USER anonymous");
       System.out.println(in.readLine());
         out.println("PASS xyx@yc.shu.edu.cn");
       System.out.println(in.readLine());
         out.println("TYPE A");
       System.out.println(in.readLine());
         out.println("PORT 202,120,127,202,4,51");
       System.out.println(in.readLine());
         out.println("LIST");
       System.out.println(in.readLine());
         out.println("CWD incoming");
       System.out.println(in.readLine());
         out.println("PWD");
       System.out.println(in.readLine());
         out.println("QUIT");
       System.out.println(in.readLine());
    } catch (Exception e) {
            System.out.println(e);
       }
    }
}
--
※ 来源:·听涛站 tingtao.dhs.org·[FROM: 匿名天使的家] 
[百宝箱] [返回首页] [上级目录] [根目录] [返回顶部] [刷新] [返回]
Powered by KBS BBS 2.0 (http://dev.kcn.cn)
页面执行时间:3.006毫秒