欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

使用UDP协议编写一个具有客户端和服务端的数据传输程序

程序员文章站 2022-06-06 16:56:46
...

使用UDP协议编写一个具有客户端和服务端的数据传输程序

客户端代码

package UDP;

import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoConnector;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.LineDelimiter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioDatagramConnector;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.util.Scanner;

public class UDPClient {
    //传入我们需要连接的服务端的地址和端口
    private InetSocketAddress inetSocketAddress;
    //会话对象
    private IoSession session;
    //连接对象
    private IoConnector connector;
    //构造方法
    public UDPClient(String host,int port){

        inetSocketAddress = new InetSocketAddress(host,port);
    }
    public static void main(String[] args){
        //首先要实例化我们的客户端对象
        UDPClient udpClient = new UDPClient("192.168.10.62",9121);
        //设置我们的connector
        udpClient.setConnector(new NioDatagramConnector());
        //设置我们的Handler
        udpClient.getConnector().setHandler(new UDPClientHandler());
        //过滤链操作
        IoConnector connector = udpClient.getConnector();
        //日志过滤器
        connector.getFilterChain().addLast("logger",new LoggingFilter());
        //编码解码
        connector.getFilterChain().addLast("codec",new ProtocolCodecFilter(new TextLineCodecFactory(
                Charset.forName("UTF-8"),
                LineDelimiter.WINDOWS.getValue(),
                LineDelimiter.WINDOWS.getValue()
        )));
        //连接服务端语句
        ConnectFuture connectFuture = connector.connect(udpClient.getInetSocketAddress());
        //等待是否连接服务端成功,相当于转异步执行为同步执行
        connectFuture.awaitUninterruptibly();
        //连接后需要执行的操作:
        //首先咱们要获取会话对象,如果没有上面的等待的画,由于connect 是异步的
        // 咱们的session对象有可能获取不到
        udpClient.setSession(connectFuture.getSession());
        //用户自己输入想发送的信息
        System.out.println("请输入你想发送的消息:");
        Scanner scanner = new Scanner(System.in);
        while(true) {
            String message = scanner.next();
            if (message.equals("exit")){
                System.exit(0);
            } else {
                udpClient.getSession().write(message);
            }
            udpClient.getSession().write(message);
        }
    }


    public IoSession getSession() {
        return session;
    }

    public void setSession(IoSession session) {
        this.session = session;
    }

    public IoConnector getConnector() {
        return connector;
    }

    public void setConnector(IoConnector connector) {
        this.connector = connector;
    }

    public InetSocketAddress getInetSocketAddress() {
        return inetSocketAddress;
    }

    public void setInetSocketAddress(InetSocketAddress inetSocketAddress) {
        this.inetSocketAddress = inetSocketAddress;
    }
}

服务端代码

package UDPCLINET;

import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.LineDelimiter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioDatagramAcceptor;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;

public class UDPServer {
    public static final int PORT= 9121;
    public static void main(String[] args) throws IOException {
        //创建acceptor对象 用于监听客户端的请求
        NioDatagramAcceptor acceptor = new NioDatagramAcceptor();
        //得到过滤链的对象
        DefaultIoFilterChainBuilder chain = acceptor.getFilterChain();
        //将日志记录添加我们的过滤链中
        chain.addLast("logger",new LoggingFilter());
        //设置编码解码器LineDelimiter
        chain.addLast("codec",new ProtocolCodecFilter(new TextLineCodecFactory(
                Charset.forName("UTF-8"),
                LineDelimiter.WINDOWS.getValue(),
                LineDelimiter.WINDOWS.getValue()
        )));
        //设置我们handler
        acceptor.setHandler(new UDPServerHandler());
        //监听端口
        acceptor.bind(new InetSocketAddress(PORT));
        System.out.println("服务端创建完成.");
    }
}

相关标签: java