Welcome to 发呆鱼.|

发呆鱼

园龄:3年4个月粉丝:1关注:0

java网络编程

java网络编程

跟随b站“遇见狂神说”学习,地址https://www.bilibili.com/video/BV1V4411p7EF

新手上路,才学疏浅,望斧正

1 概念

ip+端口号,实现端到端的通信,即主机到主机上的应用程序的通信。

ip:定位唯一一台主机

端口号:定位主机上的应用程序。

2 tcp

tcp提供可靠的面向连接服务,基于字节流传输。

2.1 tcp通信示例

package com.demo6;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * @PackageName: com.demo6
 * @ClassName: TcpCustomer
 * @author: 
 * @date: 
 * @Description: 测试tcp连接,客户端类
 */
public class TcpCustomer {

    public static void main(String[] args) {

        Socket socket=null;
        OutputStream os=null;
        try {
            InetAddress inetAddress=InetAddress.getByName("127.0.0.1");
            int port=56233;
            socket=new Socket(inetAddress,port);

            os=socket.getOutputStream();
            os.write("你好 world".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.demo6;

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

/**
 * @PackageName: com.demo6
 * @ClassName: TcpServer
 * @author: 
 * @date: 
 * @Description: 测试tcp连接,服务器类
 */
public class TcpServer {

    public static void main(String[] args) {

        ServerSocket serverSocket=null;
        Socket socket=null;
        InputStream inputStream=null;
        ByteArrayOutputStream byteArrayOutputStream=null;
        try {
            serverSocket=new ServerSocket(56233);

            socket=serverSocket.accept();

            inputStream=socket.getInputStream();

            //管道流
            byteArrayOutputStream=new ByteArrayOutputStream();
            byte[] buff=new byte[1024];
            int len=0;
            while ((len=inputStream.read(buff))!=-1){
                byteArrayOutputStream.write(buff,0,len);
            }
            System.out.println(byteArrayOutputStream.toString());


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

            if(inputStream!=null){
                try {
                    inputStream.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();
                }
            }
        }
    }
}

2.2 tcp文件上传

//客户端修改部分
InetAddress inetAddress=InetAddress.getByName("127.0.0.1");
int port=56233;
socket=new Socket(inetAddress,port);

os=socket.getOutputStream();
File file;
FileInputStream fios=new FileInputStream(new File("D:\\WorkeSpace_Study\\Study_Note\\java 多线程学习.md"));
byte[] buff=new byte[1024];
int len=0;
while ((len=fios.read(buff))!=-1){
    os.write(buff,0,len);
}
//服务器修改
filout=new FileOutputStream(new File("receiver"));
            byte[] buff=new byte[1024];
            int len=0;
            while ((len=inputStream.read(buff))!=-1){
                filout.write(buff,0,len);
            }


3 upd

udp 是不可靠的,面向无连接的服务。是基于报文传输的。也有基于udp的可靠传输。

3.1 udp通信示例

package com.demo7;

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

/**
 * @PackageName: com.demo7
 * @ClassName: 
 * @author: 
 * @date: 
 * @Description: udp 测试
 */
public class UdpCustomer {

    public static void main(String[] args) {

        try {
            //建立一个socket
            DatagramSocket datagramSocket=new DatagramSocket();

            String msg="你好";
            InetAddress inetAddress=InetAddress.getByName("127.0.0.1");
            int port=56266;

            //建个包 数据,长度(起始),地址,端口号
            DatagramPacket packet = new DatagramPacket(msg.getBytes(), 0, msg.getBytes().length, inetAddress, port);


            //发送包
            datagramSocket.send(packet);

            datagramSocket.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
package com.demo7;

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

/**
 * @PackageName: com.demo7
 * @ClassName: UdpServer
 * @author: 
 * @date: 
 * @Description: udp 测试
 */
public class UdpServer {
    public static void main(String[] args) {

        try {
            //开放端口
            DatagramSocket datagramSocket=new DatagramSocket(56266);

            //接受数据
            byte[] buff=new byte[1024];
            DatagramPacket packet = new DatagramPacket(buff, 0, buff.length);

            datagramSocket.receive(packet);

            System.out.println(new String(packet.getData(),0, packet.getLength()));



        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}

3.2循环发送

将上面的代码改造如下;

try {
    DatagramSocket socket = new DatagramSocket();

    while (true){
        BufferedReader bufferedReader = new BufferedReader(new 		InputStreamReader(System.in));
        String data=bufferedReader.readLine();

        DatagramPacket packet = new DatagramPacket(data.getBytes(), 0, data.length(), InetAddress.getByName("127.0.0.1"), 51102);
        socket.send(packet);
        if(data.equals("bye")){
            break;
        }
    }
    socket.close();

} catch (Exception e) {
    e.printStackTrace();
}
try {
        DatagramSocket socket = new DatagramSocket(51102);

        while (true){
            byte[] buff=new byte[1024];
            DatagramPacket packet = new DatagramPacket(buff, 0, buff.length);
            socket.receive(packet);


            String msg=new String(packet.getData(), packet.getOffset(), packet.getLength());
            System.out.println("接收:"+msg);
            if(msg.equals("bye")){
                break;
            }
        }

        socket.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

将接收发送代码放入run中,即可实现两边同时接收发送。

本文作者:发呆鱼

本文链接:https://www.cnblogs.com/dyiblog/articles/15786088.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   发呆鱼  阅读(44)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起