java之网络编程

Java的网络通信简单来说就是服务器端通过ServerSocket建立监听,客户端通过Socket连接到服务器,通信双方就可以通过IO流进行通信。

当一个程序需要发送数据时,需要指定目的地的IP地址和端口,如果指定了正确的IP地址和端口号,计算机网络就可以将数据送给该IP地址和端口号对应的程序。

Java使用InetAddress类来代表IP地址,它有两个子类Ine4tAddress和Inet6Address

InetAddress没有构造器,用静态方法获取InetAddress实例,例如static InetAddress getByName(String host);static InetAddress getByAddress(byte[] address);

URLEncoder和URLDecoder用于完成普通字符串到application/x-www-form-urlencoded MIME字符串之间的相互转换。在开发文档中写到:
URLEncoder
This class contains static methods for converting a String to the application/x-www-form-urlencoded MIME format.

转换的规则:

1、The alphanumeric characters “a” through “z”, “A” through “Z” and “0” through “9” remain the same.
2、The special characters “.”, “-“, “*”, and “_” remain the same.
3、The plus sign “+” is converted into a space character ” ” .
4、A sequence of the form “%xy” will be treated as representing a byte where xy is the two-digit hexadecimal representation of the 8 bits. Then, all substrings that contain one or more of these byte sequences consecutively will be replaced by the character(s) whose encoding would result in those consecutive bytes. The encoding scheme used to decode these characters may be specified, or if unspecified, the default encoding of the platform will be used.

URL(Uniform Resource Locator)对象代表统一资源定位器,指向互联网资源的指针。URL由协议名、主机、端口和资源组成。
protocal://host:port/resourceName
URI(Uniform Resource Identifiers)类,它的实例代表统一资源标识符,不能用于定位任何资源,唯一的作用就是解析。与此对应的是URL包含一个可打开到该资源的输入流,可以将URL理解成URI的特例。

URLConnection openConnection()方法一般就是建立了连接,返回URLConnection 对象,在设置好请求属性之后用connect()方法建立实际的连接。

openStream()方法是 openConnection().getInputStream()的简化而已。

public final InputStream openStream():
Opens a connection to this URL and returns an InputStream for reading from that connection. This method is a shorthand for:
openConnection().getInputStream()

一般创建一个和URL的连接,并发送请求,读取此URL引用的资源需要如下几个步骤:
1、通过调用URL对象的OpenConnection()方法创建URLConnection对象。
2、设置URLConnection的参数和普通请求属性。
3、如果只是发送GET方式请求,则用Connect()方法建立和远程资源之间的实际连接即可;如果需要发送POST方式的请求,则需要获取URLConnection实例对应的输出流来发送请求参数。
4、远程资源变为可用,程序可以访问远程资源的头字段或通过输入流读取远程资源的数据。

GET方法:
URLConnection openConnection()方法一般就是建立了连接返回URLConnection 对象,在设置好请求属性之后用connect()方法建立实际的连接。

POST方法:
发送POST请求一定要设置如下两行:

conn.setDoOutput(true);
conn.setDoInput(true);

然后获取输出流发送请求参数:
PrintWriter out=new PrintWriter(conn.getOutputStream());
out.print(param);
out.flush();

In general, creating a connection to a URL is a multistep process:
1、The connection object is created by invoking the openConnection method on a URL.
2、The setup parameters and general request properties are manipulated.
3、The actual connection to the remote object is made, using the connect method.
4、The remote object becomes available. The header fields and the contents of the remote object can be accessed.

The setup parameters are modified using the following methods:
setAllowUserInteraction
setDoInput
setDoOutput
setIfModifiedSince
setUseCaches

and the general request properties are modified using the method:
setRequestProperty

The following methods are used to access the header fields and the contents after the connection is made to the remote object:
1、getContent
2、getHeaderField
3、getInputStream
4、getOutputStream

Certain header fields are accessed frequently. The methods:
1、getContentEncoding
2、getContentLength
3、getContentType
4、getDate
5、getExpiration
6、getLastModifed

一般下载文件的步骤是这样的:
1、创建URL对象
2、获取指定URL对象所指向资源的大小(通过getContentLength()方法获得)
3、在本地磁盘上创建一个与网络资源具有相同大小的空文件
4、计算每个线程应该下载网络资源的哪个部分
5、依次创建、启动多个线程来下载网络资源的指定部分

java使用Socket对象代表两端的通信端口,并通过Socket产生IO流来进行网络通信。

使用ServerSocket创建TCP客户端
This class implements server sockets. A server socket waits for requests to come in over the network. It performs some operation based on that request, and then possibly returns a result to the requester.

客户端通常可以使用Socket的构造器来连接到指定服务器。
This class implements client sockets (also called just “sockets”). A socket is an endpoint for communication between two machines.

客户端一般是创建一个无连接的Socket,再调用Socket的connect()方法来连接服务器,在connect()方法可以接收一个超时时长参数。

下面写了一个简单的客户端向服务器上传图片的例子:

服务器端:

public class UploadImageServer {

public static void main(String[] args) throws IOException {
    // TODO Auto-generated method stub
    @SuppressWarnings("resource")
    ServerSocket ss=new ServerSocket(29999);
    while(true){
        Socket s = ss.accept();
        InputStream is=s.getInputStream();
        byte[] b=new byte[1024];
        int len=0;
        try(
            FileOutputStream fos=new FileOutputStream("./src/net/socket/new123.png"))
        {
            while((len=is.read(b))>0){
                fos.write(b, 0, len);
            }
        }
    }
}

}

客户端:

public class UploadImageClient {

public static void main(String[] args) throws UnknownHostException, IOException {
    // TODO Auto-generated method stub
    Socket socket =new Socket();
    socket.connect(new InetSocketAddress("127.0.0.1", 29999), 10000);
    OutputStream os = socket.getOutputStream();
    try(
        FileInputStream fis = new FileInputStream("./src/net/socket/123.jpg"))
    {
        byte[] b=new byte[1024];
        int len=0;
        while((len=fis.read(b))>0){
            os.write(b, 0, len);
        }
    }
    socket.close();
}

}
“`

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值