【JAVASE(2)】JAVASE实现udp&tcp通信小案例

一、udp协议下的聊天案例实现
客户端

public class UDPCli {
    public static void main(String[] args) throws Exception {
        Scanner scanner = new Scanner(System.in);
        DatagramSocket socket = new DatagramSocket();

        while (true) {
            System.out.println("请输入:");
            String CMessage=scanner.next();
            if("goodbye".equals(CMessage)){
                break;//通过goodbye使得对话结束
            }
            byte[] cMessageBytes = CMessage.getBytes();
            InetAddress address = InetAddress.getByName("127.0.0.1");
            //InetAddress address = InetAddress.getByName("224.0.1.0");绑定组播地址
            //InetAddress address = InetAddress.getByName("225.225.225.225");绑定广播地址
            int port=20000;
            DatagramPacket datagramPacket = new DatagramPacket(cMessageBytes, cMessageBytes.length, address, port);
            socket.send(datagramPacket);
        }
        socket.close();
    }
}

服务器端

public class UDPSer {
    public static void main(String[] args) throws Exception {
        //MulticastSocket socket = new MulticastSocket(20000);//组播socket
        //socket.joinGroup(InetAddress.getByName("224.0.1.0"));//绑定组播ip
        DatagramSocket socket = new DatagramSocket(20000);
        while (true) {
            byte[] serverResave = new byte[1024];
            DatagramPacket datagramPacket = new DatagramPacket(serverResave, serverResave.length);
            socket.receive(datagramPacket);

            byte[] data = datagramPacket.getData();
            int length = datagramPacket.getLength();

            System.out.println(new String(data,0,length));
        }
//        socket.close();
    }
}

二、TCP协议下的通信案例实现
客户端

public class TCPCli {
    public static void main(String[] args) throws IOException {
        Socket socket = new Socket("127.0.0.1", 20000);
        OutputStream os = socket.getOutputStream();
        os.write("客户端数据".getBytes());
        socket.shutdownOutput();

        BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        String line;
        while ((line=is.readLine())!=null){
            System.out.println(line);
        }

        is.close();
        os.close();
        socket.close();
    }
}

服务器端

public class TCPSer {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(20000);
        Socket accept = serverSocket.accept();
        BufferedReader is = new BufferedReader(new InputStreamReader(accept.getInputStream()));


        String line;
        while ((line=is.readLine())!=null){
            System.out.println(line);
        }

        BufferedWriter os = new BufferedWriter(new OutputStreamWriter(accept.getOutputStream()));
        os.write("服务端数据");
        os.newLine();
        os.flush();

        os.close();
        is.close();
        accept.close();
        serverSocket.close();
    }
}

三、带gui界面的网络聊天案例
客户端

public class GUIClient {

    public static void main(String[] args) {
        // 创建窗体
        JFrame f = new JFrame("客户端");
        f.setLayout(null);
        // 设置大小和位置
        f.setSize(400, 300);
        f.setLocation(100, 200);

        JButton b = new JButton("发送");
        b.setBounds(290, 220, 80, 30);
        f.add(b);

        JTextField tf = new JTextField();
        tf.setBounds(10, 220, 260, 30);
        f.add(tf);

        JTextArea ta = new JTextArea();
        ta.setBounds(10, 10, 360, 200);
        f.add(ta);

        f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        f.setVisible(true);

        try {
            Socket s = new Socket("127.0.0.1", 8888);

            b.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    // 获取输入文本
                    String text = tf.getText();
                    Date date = new Date();
                    SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm:ss");
                    String now = sdf.format(date);
                    ta.append(now +"\r\n我:" + text + "\r\n");
                    // 设置输入框为空
                    tf.setText("");
                    // 发送信息
                    try {
                        DataOutputStream dos = new DataOutputStream(s.getOutputStream());
                        dos.writeUTF(text);
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
            });
            // 接收信息线程
            new Thread() {
                @Override
                public void run() {
                    while (true) {
                        try {
                            // 获取其他用户的输入
                            DataInputStream dis = new DataInputStream(s.getInputStream());
                            String text = dis.readUTF();
                            String ip = s.getInetAddress().getHostAddress();
                            Date date = new Date();
                            SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm:ss");
                            String now = sdf.format(date);
                            // 添加到页面上
                            ta.append(now + "\r\n" + ip + ":" + text + "\r\n");
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

服务器端

public class GUIServer {

    public static void main(String[] args) {
        // 创建窗体
        JFrame f = new JFrame("服务器");
        f.setLayout(null);
        // 设置大小和位置
        f.setSize(400, 300);
        f.setLocation(100, 200);

        JButton b = new JButton("发送");
        b.setBounds(290, 220, 80, 30);
        f.add(b);

        JTextField tf = new JTextField();
        tf.setBounds(10, 220, 260, 30);
        f.add(tf);

        JTextArea ta = new JTextArea();
        ta.setBounds(10, 10, 360, 200);
        f.add(ta);

        f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        f.setVisible(true);

        try {
            ServerSocket ss = new ServerSocket(8888);
            Socket s = ss.accept();

            b.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    // 获取输入文本
                    String text = tf.getText();
                    Date date = new Date();
                    SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm:ss");
                    String now = sdf.format(date);
                    ta.append(now +"\r\n我:" + text + "\r\n");
                    ta.setCaretPosition(ta.getText().length());
                    // 设置输入框为空
                    tf.setText("");
                    // 发送信息
                    try {
                        DataOutputStream dos = new DataOutputStream(s.getOutputStream());
                        dos.writeUTF(text);
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
            });

            // 接收信息线程
            new Thread() {
                @Override
                public void run() {
                    while (true) {
                        try {
                            // 获取其他用户的输入
                            DataInputStream dis = new DataInputStream(s.getInputStream());
                            String text = dis.readUTF();
                            String ip = s.getInetAddress().getHostAddress();
                            Date date = new Date();
                            SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm:ss");
                            String now = sdf.format(date);
                            // 添加到页面上
                            ta.append(now + "\r\n" + ip + ":" + text + "\r\n");
                            ta.setCaretPosition(ta.getText().length());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

以上是今日小节,不喜勿喷,感谢理解。

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值