java网络编程(二)

java网络编程(二)

网络编程(一)

1.5 TCP

服务端
package com.gong.TCP;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

//服务端
public class TCPSeverDemo {

    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        Socket socket = null;
        InputStream is = null;
        ByteArrayOutputStream baos = null;
        try {
            //我的有一个地址
            serverSocket = new ServerSocket(9999);
            //2.等待客户端连接过来
            socket = serverSocket.accept();
            //读取客户端的消息
            is = socket.getInputStream();
            /*
            byte[] buffer = new byte[1024];
            int len;
            while((len = is.read(buffer))!=-1){
               String message = new String(buffer ,0 ,len);
                System.out.println(message);
            }
             */
            //管道流
            baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while((len = is.read(buffer))!=-1){
               baos.write(buffer ,0 ,len);
            }
            System.out.println(baos.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //关闭资源
            if(baos!=null){
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(is!=null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(socket!=null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(serverSocket!=null){
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

客户端
package com.gong.TCP;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;

//客户端
public class TCPDome1 {
    public static void main(String[] args) {
        InetAddress serverIP =null;
        Socket socket = null;
        OutputStream os = null;
        try {
            //要知道服务端的地址,端口号
            serverIP = InetAddress.getByName("127.0.0.1");
            int port = 9999 ;
            //发送消息
            socket = new Socket(serverIP,port);
            os = socket.getOutputStream();
            os.write("你好,欢迎你的到来".getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(os!=null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(socket!=null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
文件上传

服务端

package com.gong.TCP;


import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class TcpFileServer {
    public static void main(String[] args) throws Exception {
        ServerSocket serverSocket = new ServerSocket(9000);
        //等待客服端的连接
        Socket accpt = serverSocket.accept();

        InputStream is = accpt.getInputStream();

        FileOutputStream fos = new FileOutputStream(new File("resive.jpg"));
        int len;
        byte[] butter = new byte[1024];
        while ((len = is.read(butter))!=-1) {
            fos.write(butter,0,len);
        }

        fos.close();
        is.close();
        accpt.close();
        serverSocket.close();


    }
}

客户端

package com.gong.TCP;


import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

//客户端
public class TcpFileCilce {
    public static void main(String[] args) throws Exception {
        //需要知道服务端的地址和端口
        int port = 9000;
        Socket socket = new Socket(InetAddress.getByName("127.0.0.1"),port);

        OutputStream os = socket.getOutputStream();

        //读取文件
        FileInputStream fis = new FileInputStream(new File("anime.jpg"));

        byte[] bttfer = new byte[1024];
        int len;
        while((len = fis.read(bttfer))!=-1){
            os.write(bttfer,0,len);
        }

        //告知服务端,我已经传输完了
        socket.shutdownOutput();
//        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        fis.close();
        os.close();
        socket.close();
    }
}

1.6 Tomcat

服务端

  • 自定义 S
  • Tomcat服务器 S

客户端

  • 自定义 C
  • 浏览器 B

1.7 UDP

相当于发短信:不用连接,但需要知道对方的地址

发送端:

package com.gong.UDP;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.Socket;

public class UdpClientDome {
    public static void main(String[] args) throws Exception {
        //建立一个Socet
        DatagramSocket socket = new DatagramSocket();
        //建个包
        String msg = "你好,服务器";
        int port = 9090;
        InetAddress inetAddress =InetAddress.getByName("127.0.0.1");
        //数据,数据的长度起始,地址,端口
        DatagramPacket packet = new DatagramPacket(msg.getBytes(),0,msg.getBytes().length,inetAddress,port);
        //发送包
        socket.send(packet);

        //关闭流
        socket.close();
    }
}

接收端:

package com.gong.UDP;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UDPserverDome {
    public static void main(String[] args) throws Exception {
        DatagramSocket socket = new DatagramSocket(9090);
        //接收数据包
        byte[] butter = new byte[1024];
        DatagramPacket packet = new DatagramPacket(butter,0,butter.length);
        //接收包
        socket.receive(packet);
        System.out.println(new String(packet.getData(),0,packet.getData().length));

        //关闭连接
        socket.close();
    }
}

聊天室:

发送方:

package com.gong.UDPChat;

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

public class UdpSenderDemo {
    public static void main(String[] args) throws Exception {
        DatagramSocket socket = new DatagramSocket(6666);

        //准备输入数据

        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        while(true) {
            String data = reader.readLine();
            byte[] datas = data.getBytes();
            DatagramPacket packet = new DatagramPacket(datas, 0, datas.length, new InetSocketAddress("localhost", 8777));

            //发送数据
            socket.send(packet);
            if(data.equals("bye")){
                break;
            }
        }

        //关闭连接
        socket.close();
    }

}

接收方:

package com.gong.UDPChat;

import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class UdpReciveDome {
    public static void main(String[] args) throws Exception  {
        DatagramSocket socket = new DatagramSocket(8777);
        while(true) {
            byte[] butter = new byte[1024];
            DatagramPacket packet = new DatagramPacket(butter, 0, butter.length);
            socket.receive(packet);

            byte[] data = packet.getData();
            String receiveDatas = new String(data, 0, data.length);
            System.out.println(receiveDatas);
            if (receiveDatas.equals("bye")) {
                break;
            }
        }
        //关闭连接
        socket.close();
    }
}

实现多线程聊天:

发送接口

package com.gong.UDPChat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;

public class TalkSend  implements Runnable {
    DatagramSocket socket = null;
    DatagramPacket packet = null;
    BufferedReader reader = null;
    private int fromPort;
    private String toIP;
    private  int toPort;

    public TalkSend(int fromPort, String toIP, int toPort) {
        this.fromPort = fromPort;
        this.toIP = toIP;
        this.toPort = toPort;

        try {
            socket = new DatagramSocket(fromPort);
            reader = new BufferedReader(new InputStreamReader(System.in));
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        while(true) {
            try {
                String data = reader.readLine();
                byte[] butter = data.getBytes();
                packet = new DatagramPacket(butter, 0, butter.length, new InetSocketAddress(toIP, toPort));
                socket.send(packet);
                if (data.equals("bye")){
                    break;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        socket.close();
    }
}

接收接口:

package com.gong.UDPChat;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class TalkRecevie implements Runnable{
    DatagramSocket socket = null;
    DatagramPacket packet = null;
    private int fromIP;
    private String name;

    public TalkRecevie(int fromIP,String name) {
        this.fromIP = fromIP;
        this.name = name;
        try {
            socket = new DatagramSocket(fromIP);
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        try {
            while(true){
                byte[] butter = new byte[1024];
                packet = new DatagramPacket(butter,0,butter.length);
                socket.receive(packet);

                byte[] data = packet.getData();
                String msg = new String(data,0,data.length);
                System.out.println(name+msg);
                if(msg.equals("bye")){
                    break;
                }
            }
        }catch (IOException e) {
            e.printStackTrace();
        }
        socket.close();
    }
}

实现聊天:

package com.gong.UDPChat;

public class student {
    public static void main(String[] args) {
        new Thread(new TalkSend(7777,"localhost",8888)).start();
        new Thread(new TalkRecevie(9999,"老师:")).start();
    }
}
package com.gong.UDPChat;

public class teacher {
    public static void main(String[] args) {
        new Thread(new TalkSend(8222,"localhost",9999)).start();
        new Thread(new TalkRecevie(8888,"学生:")).start();
    }
}

1.8 Url

https://www.baidu.com/

协议:// IP地址:端口/资源

统一资源定位符:定位资源的,定位互联网上的某一个资源的

DNS域名解析: 把www.daidu.com解析成xxx.xx.xx.x的IP地址

import java.net.MalformedURLException;
import java.net.URL;

public class UrlDome {
    public static void main(String[] args) throws MalformedURLException {
        URL url = new URL( "http://localhost:8080/hel1owor1d/index.jsp?username=lihua&password=123456");
        System. out. println(url.getProtocol()); //协议
        System. out . println(url.getHost()); //主机ip
        System. out. println(url.getPort()); //端口
        System. out . println(url.getPath()); //文件路径
        System. out. println(url.getFile()); //全路径
        System. out . println(url. getQuery()); //参数
    }
}

下载文件

package com.gong.URL;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;

import java.net.URL;

public class UrlDome {
    public static void main(String[] args) throws Exception {
        //下载地址
        URL url = new URL("http://localhost:8080/hollewrold/holle.txt");
        //连接到这个资源 HTTp
        HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();

        InputStream is = urlConnection.getInputStream();

        FileOutputStream fos = new FileOutputStream("holle.txt");

        byte[] buffer = new byte[1024];
        int len;
        while((len = is.read(buffer))!=-1){
            fos.write(buffer,0,len);
        }
        fos.close();
        is.close();
        urlConnection.disconnect();//断开连接

    }
}

这是在b站上看的java基础,比较好的视频,大家去学学狂神说java的视频网络基础

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值