Java网络编程学习笔记

网络编程

1.TCP消息发送

1.1客户端

  1. 连接服务器Socket

  2. 发送消息

package com.chen.net;

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

public class Customer {
    public static void main(String[] args) {
        Socket s=null;
        OutputStream os=null;
        try{
            //获取地址
            InetAddress ia=InetAddress.getByName("localhost");
            int port=8888;
            //建立连接
            s=new Socket(ia,port);
            //发送消息 IO流
            os=s.getOutputStream();
            os.write("hello~".getBytes());
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally{
            if(os!=null)
                try{
                    os.close();
                }
            catch (Exception e)
            {
                e.printStackTrace();
            }
            if(s!=null)
                try{
                    s.close();
                }
            catch (Exception e)
            {
                e.printStackTrace();
            }

        }
    }
}

1.2服务器

  1. 建立服务端口ServerSocket

  2. 等待用户连接accept

  3. 接受客户端消息

package com.chen.net;

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

public class Service {
    public static void main(String[] args) throws IOException {
        ServerSocket ss=null;
        Socket s=null;
        InputStream is=null;
        ByteArrayOutputStream bao=null;
        try{
            //设置地址
            ss=new ServerSocket(8888);
            //等待客户端连接过来
            while(true){
                try{
                    ss.setSoTimeout(50000);
                }
                catch (Exception e)
                {
                    break;
                }
                s=ss.accept();
                is=s.getInputStream();
                //读取客户端消息
                byte[] ac=new byte[1024];
                int len;
                //管道流
                bao=new ByteArrayOutputStream();
                while((len=is.read(ac))!=-1)
                {
                    bao.write(ac,0,len);
                }
                System.out.println(bao.toString());
            }

        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        finally{
            if(bao!=null)
                try
                {
                    bao.close();
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            if(is!=null)
                try
                {
                    is.close();
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            if(s!=null)
                try
                {
                    s.close();
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            if(ss!=null)
                try
                {
                    ss.close();
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            System.out.println("通信结束!");
        }
    }
}

2.TCP实现文件上传

类似TCP实现聊天

2.1服务器

package com.chen.net;

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

public class Service {
    public static void main(String[] args) throws IOException {
        ServerSocket ss=null;
        Socket s=null;
        InputStream is=null;
        FileOutputStream bao=null;
        try {
                //1.设置地址
                ss = new ServerSocket(8888);
               while(true) {

                //2.等待客户端连接
                s = ss.accept();

                //3.获取输入流
                is = s.getInputStream();
                byte[] ac = new byte[1024];
                int len;
                
                //4.文件输出
                bao = new FileOutputStream("service.JPG");
                while ((len = is.read(ac)) != -1) {
                    bao.write(ac, 0, len);
                }

                //5.通知客户端我收到了文件
                OutputStream outputStream = s.getOutputStream();
                outputStream.write("我收到了,可以关闭连接了~".getBytes());
                
                //6.通知客户端我的消息传输完毕
                s.shutdownOutput();
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        finally{
            if(bao!=null)
                try
                {
                    bao.close();
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            if(is!=null)
                try
                {
                    is.close();
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            if(s!=null)
                try
                {
                    s.close();
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            if(ss!=null)
                try
                {
                    ss.close();
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            System.out.println("通信结束!");
        }
    }
}

2.2客户端

package com.chen.net;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;

public class Customer {
    public static void main(String[] args) {
        Socket s=null;
        OutputStream os=null;
        try{
            //1.获取地址
            InetAddress ia=InetAddress.getByName("localhost");
            int port=8888;

            //2.建立连接
            s=new Socket(ia,port);

            //3.上传文件
            os=s.getOutputStream();
            FileInputStream fis=new FileInputStream("src/test.JPG");
            byte[] buffer=new byte[1024];
            int len;
            while((len=fis.read(buffer))!=-1)
            {
                os.write(buffer,0,len);
            }

            //4.通知服务器端我已经传输完了
            s.shutdownOutput();

            //5.确认服务器接收完毕
            InputStream inputStream=s.getInputStream();
            ByteArrayOutputStream bao=new ByteArrayOutputStream();
            byte[] buffer2=new byte[1024];
            int len1;
            while((len1=inputStream.read(buffer2))!=-1)
            {
                bao.write(buffer2,0,len1);
            }
            System.out.println(bao.toString());
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally{
            if(os!=null)
                try{
                    os.close();
                }
            catch (Exception e)
            {
                e.printStackTrace();
            }
            if(s!=null)
                try{
                    s.close();
                }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }
}

3.UDP消息发送

3.1发送端

  1. 建立DatagramSocket

  2. 新建包

  3. 发送包

package com.chen.net.udp;

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

public class udpClientDemo {
    public static void main(String[] args) throws IOException {
        //1.建立DatagramSocket
        DatagramSocket ds=new DatagramSocket();

        //2.建立包
        String msg="你好,服务器~";
        InetAddress ia=InetAddress.getByName("localhost");
        int port=8090;

        //数据、起点、长度、发送给谁
        DatagramPacket dp=new DatagramPacket(msg.getBytes(),0,msg.getBytes().length,ia,port);

        //3.发送包
        ds.send(dp);
        ds.close();
    }
}
   

3.2接收端

  1. 开放端口
  2. 接收数据包
package com.chen.net.udp;

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

public class udpServerDemo {
    public static void main(String[] args) throws IOException {
        //1.开放端口
        DatagramSocket ds=new DatagramSocket(8090);
        //2.接收数据包
        byte[] buffer=new byte[1024];
        DatagramPacket dp=new DatagramPacket(buffer,0,buffer.length);
        ds.receive(dp);  //阻塞接收
        System.out.println(dp.getAddress().toString());
        System.out.println(new String(buffer,0,buffer.length));
        ds.close();
    }
}

4.UDP实现文件上传

4.1发送端

package com.chen.net.udp;

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

public class udpClientDemo {

    public static void main(String[] args) throws IOException {
        DatagramSocket ds=null;
        DatagramPacket dp=null;
        try
        {
            //1.建立DatagramSocket
            ds=new DatagramSocket();

            //2.建立包
            byte[] buffer=IoUtils.fileToByteArray("src/test.JPG");
            InetAddress ia=InetAddress.getByName("localhost");
            int port=8090;

            //数据、起点、长度、发送给谁
            dp = new DatagramPacket(buffer, 0,buffer.length, ia, port);

            //3.发送包
            ds.send(dp);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            if(ds!=null)
                try{

                }
            catch (Exception e)
            {
                ds.close();
            }
        }
    }
}

4.2接收端

package com.chen.net.udp;

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

public class udpServerDemo {
    public static void main(String[] args) {
        DatagramSocket ds=null;
        try{
            //1.开放端口
            ds=new DatagramSocket(8090);

            //2.接收数据包
            byte[] buffer=new byte[1024*60];
            DatagramPacket dp=new DatagramPacket(buffer,0,buffer.length);
            ds.receive(dp);  //阻塞接收
            IoUtils.byteArrayToFile(dp.getData(),"msg.JPG");
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        finally {
            if(ds!=null)
            try{
                ds.close();
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }

    }
}

4.3工具类

package com.chen.net.udp;

import java.io.*;

public class IoUtils {
    public static byte[] fileToByteArray(String filePath){
        FileInputStream is=null;
        ByteArrayOutputStream baos=null;
        try
        {
            is=new FileInputStream(filePath);
            baos=new ByteArrayOutputStream();
            byte[] buffer=new byte[1024];
            int len;
            while((len=is.read(buffer))!=-1)
            {
                baos.write(buffer,0,len);
            }
            baos.flush();
        }
       catch(Exception e)
       {
           e.printStackTrace();
       }
        finally {
            if(is!=null)
                try{
                    is.close();
                }
            catch (Exception e)
            {
                e.printStackTrace();
            }
            if(baos!=null)
                try{
                    baos.close();
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
        }
        return baos.toByteArray();
    }
    public static void byteArrayToFile(byte[] buffer,String filePath) {
        ByteArrayInputStream bais=null;
        FileOutputStream fos=null;
        try
        {
            bais=new ByteArrayInputStream(buffer);
            fos=new FileOutputStream(filePath);
            byte[] tmp=new byte[1024];
            int len;
            while((len=bais.read(tmp))!=-1)
            {
                fos.write(tmp,0,len);
            }
            fos.flush();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        finally{
            if(bais!=null)
                try
                {
                    bais.close();   
                }
               catch(Exception e)
               {
                   e.printStackTrace();
               }
          if(fos!=null)
              try
              {
                  fos.close();
              }
          catch(Exception e)
            {
                e.printStackTrace();
            }
        }
    }
}

4.4备注

一、 while((len=bais.read(tmp))!=-1)
{
fos.write(tmp,0,len);
}

read方法的参数tmp为一次读取数据量

二、DatagramPacket dp=new DatagramPacket(buffer,0,buffer.length);
该构造器最后一个参数限定了接收数据量的大小,要避免分配空间过小导致文件失败

5.Socket与DatagramSocket的区别

Socket:使用TCP连接,需要连接成功后才能进行通信

DatagramSocket:使用UDP连接,客户端不需要连接服务端,可以直接向指定服务端发送数据

6.UDP在线咨询

核心:两个人都既是发送方,又是接收方

重点:多线程的使用

6.1发送类

package com.chen.net.realChart;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.lang.reflect.Executable;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;

public class Sender implements Runnable{
    private String toIp;
    private int toPort;
    private DatagramSocket socket=null;
    private BufferedReader br=null;
    public Sender(String toIp, int toPort)
    {
        try
        {
            socket=new DatagramSocket();
            br=new BufferedReader(new InputStreamReader(System.in));
            this.toIp=toIp;
            this.toPort=toPort;
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        try
        {
            while(true)
            {
                String message=br.readLine();
                byte[] buffer=message.getBytes();
                DatagramPacket dp=new DatagramPacket(buffer,0,buffer.length,new InetSocketAddress(toIp,toPort));
                socket.send(dp);
                if(message.trim().equals("bye"))
                {
                    break;
                }
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            if(br!=null)
                try
                {
                    br.close();
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            if(socket!=null)
                try{
                    socket.close();
                }
            catch (Exception e)
            {
                e.printStackTrace();
            }

        }

    }
}

6.2接收类

package com.chen.net.realChart;

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

public class Receiver implements Runnable{
    private DatagramSocket socket=null;
    private String fromName=null;
    public Receiver(int port, String fromName)
    {
        try
        {
            this.socket=new DatagramSocket(port);
            this.fromName=fromName;
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }

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

                byte[] tmp=dp.getData();
                String message=new String(tmp,0,tmp.length);
                System.out.println(fromName+":"+message);
                if(message.trim().equals("bye"))
                {
                    break;
                }

            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        finally {
            if(socket!=null)
                try{
                    socket.close();
                }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }
}

6.3咨询对象一:老师

package com.chen.net.realChart;

public class Teacher {
    private static String talker="学生";
    public static void main(String[] args)
    {
        new Thread(new Sender("localhost",1234)).start();
        new Thread(new Receiver(9494,talker)).start();
    }
}

6.4咨询对象二:学生

package com.chen.net.realChart;

public class Student {
    private static String talker="老师";
    public static void main(String[] args)
    {
        new Thread(new Sender("localhost",9494)).start();
        new Thread(new Receiver(1234,talker)).start();
    }
}

7.利用URL下载文件

package com.chen.net.downFile;

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

public class urlDown{
    public static void main(String[] args) throws IOException {
        //1.获取URL
        URL url=new URL("https://webfs.yun.kugou.com/202010241707/7df53cca785a2d34d113623e9da22466/part/0/960931/G112/M01/06/00/EIcBAFw0EIqAUjs5AClSIVJy_ec396.mp3");

        //2.打开连接
        HttpURLConnection connection=(HttpURLConnection)url.openConnection();

        InputStream inputStream=connection.getInputStream();

        FileOutputStream fos=new FileOutputStream("f2.mp3");

        //3.下载
        byte[] buffer=new byte[1024];
        int len;
        while((len=inputStream.read(buffer))!=-1)
        {
            fos.write(buffer,0,len);
        }
        fos.close();
        inputStream.close();
        connection.disconnect();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值