java网络编程之基于UDP的socket编程

在A端创建窗体,窗体中有一个输入文本控件,在文本行输入字符,B端进行接收。

//A端
package UdpTri;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.*;
import java.io.*;

/**
 * @author laura li
 */

public class UdpClient {
    static JTextField jtf;
    static String text;
    private static void Gui(){
        JFrame f=new JFrame("draw triangle");                 
        f.setSize(800,600);
        jtf = new JTextField();
        f.add(jtf,"South");
        f.setVisible(true);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jtf.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent arg0) {
                text = jtf.getText();
                jtf.setText("");
                System.out.println(text);
                byte[] buf = text.getBytes();
                InetAddress serveIpAddress = null;
                try {
                    serveIpAddress = InetAddress.getByName("127.0.0.1");
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                try {
                    DatagramSocket socket = new DatagramSocket();
                    DatagramPacket dp = new DatagramPacket(buf, buf.length, serveIpAddress, 4445);
                    socket.send(dp);
                } catch (SocketException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public static void main(String[] args)throws Exception{
        Gui();
    }

}
//B端
package UdpTri;
import java.net.*;
import java.io.*;

public class UdpServer{
    public static void main(String[] args)throws Exception{
        DatagramSocket socket = new DatagramSocket(4445);
        byte[] buf=new byte[1024]; //创建缓冲区
        DatagramPacket dp = new DatagramPacket(buf, buf.length);
        socket.receive(dp);
        String str = new String(dp.getData(), 0, dp.getLength());   //从0到总长转换为String

    }
}

猜你喜欢

转载自blog.csdn.net/LJH_laura_li/article/details/83065242