自己学习java所整理的网络编程知识

package Url;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;

public class URLReaader {
    public static void main(String[] args) throws Exception{//主方法抛弃异常
        URL cs = new URL("https://www.sina.com.cn/");
        BufferedReader in = new BufferedReader(new InputStreamReader(cs.openStream()));
        String inputLine;
        while ((inputLine = in.readLine())!=null)
            System.out.println(inputLine);
        in.close();
    }
}
URL:一致资源定位器的简称,他表示Interent上某一资源的地址
构造URL对象
    1.public URL(String spec)
        URL urlBase = new URL("http://www.gamelan.com/");
    2.public URL(URL context,String spec)
        URL gamelan = 
            new URL("http://www.gamelan.com/pages/");
        URL gamelanGames =
            new URL(gamelan,"Gamelan.game.html");
        URL gamelanNetwork = 
            new URL(gamelan,"Gamelan.net.html");
    3.public URL(String protocol,String host,String file);
        new URL("http","www.gamelan.com","/pages/Gamelan.net.html");
    4.public URL(String protocol,String host,int port,String file);
        URL gamelan = new URL("http","www.gamelan.com","80","pages/Gamelan.network.html");

    
构造URL对象一定要进行例外处理
    try{
         URL myURL = new URL(...)
}catch(MalformedURLException e){
    ...
    // exception handler code here
    ...

}

获取URL对象属性
    public String getProtocol()//协议
    public String getHost()  //主机名
    public String getPort()    //端口号
    public String getFile()  //文件名
    public String getRef()    //引用地址
    

URLConnection
    1.一个URLConnection对象代表一个URL资源与java程序的通讯连接,可以通过
    它对这个URL资源读或写
    2.与URL的区别
        1)一个单向,一个双向
        2)可以查看服务器的响应消息的首部
        3)可以设置客户端请求消息的首部

使用URLConnection通信的一般步骤
    1.构造一个URL对象
    2.调用URL对象的openConnection()方法获取对应该URL的URLConnection对象
    3.配置此URLConnection对象
    4.读取首部字段
    5.获得输入流读取数据
    6.获得输出流写入数据
    7.关闭连接
import java.io.*;
import java.net.*;

public class URLConnector {
    public static void main(String[] args) {
        try {
            URL cs = new URL("https://www.sina.com.cn/");
            URLConnection tc = cs.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(tc.getInputStream()));
            String inputLine;
            while ((inputLine = in.readLine())!=null)
                System.out.println(inputLine);
            in.close();
        }catch (MalformedURLException e){
            System.out.println("MalformedURLException ");
        }
        catch (IOException e){
            System.out.println("IOException");
        }
    }
}

发送GET请求
发送POST请求
    POST请求的参数需要通过URLConnection的输出流来写入参数


HttpURLConnection类
    1.在URLConnection的基础上提供一系列针对http请求的内容
        1)HTTP状态码(例如HTTP_OK:200)
        2)setRequestMethod(设置请求方法GET\POST等)
        3)getResponseCode(获取HTTP的响应)


TCP传输协议
    面向连接的能够提供可靠的流式数据传输的协议。类似于打电话的过程。
     URL,URLConnection,Socket,ServerSocket等类都使用TCP协议进行网络通讯

socket通讯
    1.网络上的两个程序通过一个双向的通讯连接实现数据的交换,这个双向链路的一端
    称为一个socket
    2.socket通常用来实现客户方和服务方的连接


Client------》(Request)     Server
        (Response)《----
    (ClientSocket)    (ServerSocket)

创建socket
    Socket()
    Socket(InetAddress address,int port);
    Socket(String host,int port);
    Socket(InetAddress host, int port,InetAddress localAddr,int localPort)
    Socket(String host,int port,InetAddress localAddr,int localPort)
客户端Socket的建立
服务器端Socket的建立
打开输入/输出流
关闭socket
os.close();
is.close();
socket.close();
注意关闭的顺序

客户端
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class TalkClient {
    public static void main(String[] args) {
        try {
            Socket socket = new Socket("127.0.0.1",4700 );
            BufferedReader sin = new BufferedReader(new InputStreamReader(System.in));
            PrintWriter os = new PrintWriter(socket.getOutputStream());
            BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String readline;
            readline = sin.readLine();
            while (!readline.equals("bye")){
                os.println(readline);
                os.flush();
                System.out.println("Client:"+readline);
                System.out.println("Server:"+is.readLine());
                readline=sin.readLine();
            }
            os.close();
            is.close();
            socket.close();
        }catch (Exception e){
            System.out.println("Error"+e);
        }
    }
}
服务器端
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class TalkServer {
    public static void main(String[] args) {
        try {
            ServerSocket server = null;
            try {
                server = new ServerSocket(4700);
            }catch (Exception e){
                System.out.println("can not listen to:"+e);
            }
            Socket socket = null;
            try {
                socket = server.accept();
            }catch (Exception e){
                System.out.println("Error:"+e);
            }
            String line;
            BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            PrintWriter os = new PrintWriter(socket.getOutputStream());
            BufferedReader sin = new BufferedReader(new InputStreamReader(System.in));
            System.out.println("Client:"+is.readLine());
            line = sin.readLine();
            while (!line.equals("bye")){
                os.println(line);
                os.flush();
                System.out.println("Server:"+line);
                System.out.println("Client:"+is.readLine());
                line = sin.readLine();
            }
            os.close();
            is.close();
            socket.close();
            server.close();
        }catch (Exception e){
            System.out.println("Error:"+e);
        }
    }
}

Socket多客户机制实现
服务器端
package duoxianchenlt;

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

public class MultiTalkServer {
    static int clientnum = 0;

    public static void main(String[] args) throws IOException {

        ServerSocket serverSocket = null;
        boolean listening = true;
        try {
            serverSocket= new ServerSocket(4700);
        }catch (IOException e){
            System.out.println("Could not listen on port:4700.");
            System.exit(-1);
        }
        while (listening){
            new ServerThread(serverSocket.accept(),clientnum).start();
            clientnum++;
        }
        serverSocket.close();
    }
}
客户端
package duoxianchenlt;

import java.io.*;
import java.net.*;
public class MultiTalkClient {
    int num;

    public static void main(String[] args) {
        try {
            Socket socket = new Socket( "127.0.0.1",4700);
            BufferedReader sin = new BufferedReader(new InputStreamReader(System.in));
            PrintWriter os = new PrintWriter(socket.getOutputStream());
            BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String readline;
            readline = sin.readLine();
            while (!readline.equals("bye")){
                os.println(readline);
                os.flush();
                System.out.println("Client:"+readline);
                System.out.println("Server:"+is.readLine());
                readline = sin.readLine();
            }
            os.close();
            is.close();
            socket.close();
        }catch (Exception e){
            System.out.println("Error:"+e);
        }
    }
}
线程
package duoxianchenlt;

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

public class ServerThread extends Thread{
    Socket socket = null;
    int clientnum;
    public ServerThread(Socket socket,int num){
        this.socket = socket;
        clientnum = num+1;
    }
    public void run(){
        try{
            String line;
            BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            PrintWriter os = new PrintWriter(socket.getOutputStream());
            BufferedReader sin = new BufferedReader(new InputStreamReader(System.in));
            System.out.println("Client"+clientnum+":"+is.readLine());
            line = sin.readLine();
            while (!line.equals("bye")){
                os.println(line);
                os.flush();
                System.out.println("Server:"+line);
                System.out.println("Client:"+clientnum+":"+is.readLine());
                line = sin.readLine();
            }
            os.close();
            is.close();
            socket.close();
        }catch (Exception e){
            System.out.println("Error:"+e);
        }
    }
}


数据报通信
UDP:
    非面向连接的提供不可靠的数据包式的数据传输的协议。类似于从邮局发送信件的过程
    DatagramPacket,DatagramSocket,MulticastSocket等类使用UDP协议进行网络通讯
TCP:面向连接的能够提供可靠的流式数据传输的协议。类似于打电话的过程。
    URL,URLConnection,Socket,ServerSocket等类都使用TCP协议进行网络通讯


区别:
    1.TCP有建立时间
    2.UDP传输有大小限制:64k以内
    3.TCP的应用:Telnet,ftp
      UDP的应用:ping
    
构造数据报通信
    DatagramSocket()
    DatagramSocket(int port)
    DatagramPacket(byte ibuf[],int ilength) //接收
    DatagramPacket(byte ibuf[],int ilength,InetAddress iaddr,int iport) //发送


收数据报
    DatagramPacket packet = new DatagramPacket(buf,256);
    socket.receive(packet);
发数据报
    DatagramPacket  packet = new DatagramPacket(buf,buf.length,address,port););
        socket.send(packet);


使用数据报进行广播通信
    1.DatagramSocket只允许数据报发往一个目的地址
    2.MilticastSocket将数据报以广播方式发送到该端口的所有客户
    3.MilticastSocket用在客户端,监听服务器广播来的数据

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

掉帧且闪退

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值