java初级网络编程二

今天接着总结些些网络编程的东西吧:

URL是UniformResource Locator的简称,即统一资源定位符,URL也是在互联网上访问的地址,相当于现实中的门牌号,一个地址对应一个资源。

其由(协议名:资源名)组成,协议名有以下几种:file(本机上的文件是指定的资源)、ftp(表示通过FTP协议来访问资源,如建立一个FTP服务器供局域网内使用)、http(表示通过HTTP协议来访问资源,平时上网都是通过这个协议来访问网站的)、https(表示通过具有安全的套接字层的HTTP协议来访问资源);资源名的组成格式为-->//<authority>:[<port>]/<path>[?<query>[#<fragment>]]quthority(表示指定服务器的主机名或IP地址)、port(表示端口号,是应用程序的标识)、path(表示路径,由零个或多个/符号隔开的字符串表示)、query(表示查询,为可选部分)、fragment(表示信息片段,也是可选部分)

URL类的构造方法:

URL(String spec):通过指定的URL字符串创建URL对象

URL(Stringprotocol,String host,int port,ing file):通过指定的协议、主机地址、端口号和路径字符串创建URL对象

URL(String protocol):通过指定的协议、主机地址和路径字符串创建URL对象

URL(URL context,Stringspec):通过在指定的上下文中对指定的协议进行解析创建URL对象

URLConnectio抽象类代表应用程序和URL之间的通信链接,此类的实例可以用于读取和写入此URL引用的资源,通常创建一个到URL的连接需要以下几个步骤:

1)对影响到远程资源连接的参数进行操作,通过在URL上调用openConnection方法创建连接对象

2)处理设置参数和一般请求属性

3)使用connect方法建立到远程对象的实际连接,与资源交互;查询头字段和内容

4)远程对象变为可用,

URL 测试:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.PipedWriter;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
public class URLTest {
    public static void main(String[] args) {
        try {
        String urlName = "http://www.51cto.com";
                                              
            URL url = new URL(urlName);
            System.out.println("print some infomation of the URL");
            System.out.println("getProtocol:"+url.getProtocol());
            System.out.println("gethost"+url.getHost());
            System.out.println("getfile:"+url.getFile());
            System.out.println("getPath:"+url.getPath());
            System.out.println("getPort:"+url.getPort());
            System.out.println("getDefaultPort"+url.getDefaultPort());
                                                  
            URLConnection connection = url.openConnection();
            connection.connect();
            System.out.println("print the infomation of Head paragraph");
            int n = 1;
            String key;
            while((key = connection.getHeaderFieldKey(n))!= null){
                String value = connection.getHeaderField(n);
                System.out.println(key+":"+value);
                n++;
            }
                                                  
                                                  
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            n = 1;
            while((line = in.readLine())!= null&&n<=5){
                System.out.println(line);
                n++;
            }
                                                  
            BufferedWriter bw = new BufferedWriter(new FileWriter("E:/URLTest.html"));
            PrintWriter pw = new PrintWriter(bw);
            String temps = null;
            while((temps = in.readLine())!= null){
                pw.print(temps);
            }
            System.out.println("down load !");
            pw.close();
            in.close();
                                                  
        } catch (Exception e) {
            e.printStackTrace();
        }
                                              
    }
}
显示出网页中的一些信息,然后将网页信息复制到指定的位置:
print some infomation of the URL
getProtocol:http
gethostwww.51cto.com
getfile:
getPath:
getPort:-1
getDefaultPort80
print the infomation of Head paragraph
Server:Tengine
Date:Mon, 12 Aug 2013 01:54:39 GMT
Content-Type:text/html
Transfer-Encoding:chunked
Connection:keep-alive
Keep-Alive:timeout=10
Vary:Accept-Encoding
Load-Balancing:web39
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>51CTO.COM - 技术成就梦想 - 中国领先的IT技术网站</title>
<meta name="description" content="中国领先的IT技术网站51CTO(www.51cto.com)是一个为CTO、IT技术经理、系统工程师、网络工程师、安全工程师、数据库工程师、网络管理员、开发工程师、项目管理人员等IT技术人员搭建的互动媒体平台,主要为IT技术人员提供新闻资讯、技术文档、BBS、博客、技术圈、培训课程、人才交流等专业服务。" />
Downloading has finished!

   UDP Socket编程:UDP的通信方式是基于无连接的、不可靠的传输协议,不保证信息的可靠、正确传输,数据报套接字DatagramSocket不需要创建两个Socket,不可以使用输入,输出流,它经常使用与网络游戏之间的通信,以及一些其他的网络应用程序,此通信方式会用到DatagramSocket类和InetAddress类:下面通过一个例子来看看其具体的使用方法:

package net;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class UDPServer {
    public static void main(String[] args) {
        byte[] bufferIn = new byte[26];
        byte[] bufferOut;
        try {
            DatagramSocket ds = new DatagramSocket(13);
            System.out.println("UDP端启动,在13端口:");
            int num = 0;
            while(num<100){
                num++;
                DatagramPacket packetIn = new DatagramPacket(bufferIn, bufferIn.length);
                                         
                ds.receive(packetIn);
                InetAddress ia = packetIn.getAddress();
                int port = packetIn.getPort();
                String str = new String(bufferIn);
                str = str.toUpperCase();
                bufferOut = str.getBytes();
                System.out.println("收到第"+num+"封信,来源IP是:"+ia.toString()+",端口号为:"+port);
                DatagramPacket packetOut = new DatagramPacket(bufferOut, bufferOut.length,ia,port);
                ds.send(packetOut);
                                         
            }
            ds.close();
        }catch (Exception e) {
                    e.printStackTrace();
                }
                                     
        }
}

下面是客户端:

package net;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
public class UDPClient {
    public static void main(String[] args) {
        byte[] bufferOut = new byte[26];
        byte[] bufferIn = new byte[26];
        for(int i=0;i<bufferOut.length;i++){
            bufferOut[i] = (byte) ('a'+i);
        }
        try {
            DatagramSocket ds = new DatagramSocket(3333);
            InetAddress ia = InetAddress.getByName("localhost");
            DatagramPacket packetOut = new DatagramPacket(bufferOut, bufferOut.length,ia,13);
            ds.send(packetOut);
            DatagramPacket packetIn = new DatagramPacket(bufferOut, bufferIn.length);
            ds.receive(packetIn);
            String str1 = new String(packetIn.getData());
            String str2 = new String(bufferIn);
            System.out.println(str1);
            System.out.println(str2);
            ds.close();
                                     
                                     
        } catch (Exception e) {
            e.printStackTrace();
        }
                                 
    }
}

   输出:ABCDEFGHIJKLMNOPQRSTUVWXYZ

   TCP Socket编程:服务器端和客户端之间的连接主要采用TCPSocket(套接字)连接,在java中提供了SocketServerSocket来来实现连接:

package net;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
public class TcpServer {
    public static void main(String[] args) {
        long count =0;
        ServerSocket ss = null;
        try {
            ss = new ServerSocket(8899);
            System.out.println("服务器对8899端口实施监听。。。");
            while(true){
                Socket s = ss.accept();
                count++;
                ServerThread serverThread = new ServerThread(s,count);
                serverThread.start();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
class ServerThread extends Thread{
    Socket socket;
    long count;
    public ServerThread(Socket socket,long c){
        this.count = c;
        this.socket = socket;  
    }
    public void run(){
        int timeCounter = 0;
                     
        try {
            InputStream is = socket.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            OutputStream os = socket.getOutputStream();
            PrintStream ps = new PrintStream(os);
            while(true){
                timeCounter++;
                String str = br.readLine();
                System.out.println(str);
                if(str.equals("exit")){
                    ps.println("exit");
                    ps.flush();
                    socket.close();
                    break;
                                 
                }
                         
            ps.println("这是:"+socket.toString()+"第"+timeCounter+"次发送转换请求,现在有"+count+"个客户在线,转换后的字符串为"+str.toUpperCase());
            ps.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

客户端:


package net;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class TcpClient {
    public static void main(String[] args) {
        try {
            Socket s = new Socket("localhost",8899);
            boolean flag = true;
            OutputStream os = s.getOutputStream();
            PrintStream ps = new PrintStream(os);
            InputStream is = s.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String str = null;
            BufferedReader kbr = new BufferedReader(new InputStreamReader(System.in));
            while(flag){
                System.out.println("请输入:");
                String inputString = kbr.readLine();
                ps.println(inputString);
                if((str = br.readLine())!=null){
                    if(str.equals("exit")){
                    flag = false;
                    }
                             
                System.out.println("服务器返回的信息:"+str);
                }
                         
            }
            s.close();
                     
        }  catch (Exception e) {
            e.printStackTrace();
        }
                 
    }
}

还需要加强对流的理解,以后需要多用。

你可能感兴趣的:(互联网,服务器,网络编程,应用程序,IP地址)