Java 初学UDP传输
不谈理论,先举简单例子。
发送端代码:
public class UDPDemo {
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket();
String str = "hello";
DatagramPacket dp = new DatagramPacket(str.getBytes(),str.length(),InetAddress.getByName("127.0.0.1"),8888);
ds.send(dp);
ds.close();
}
}
接收端代码:
public class UDPDemo2 {
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket(8888);
DatagramPacket dp = new DatagramPacket(new byte[1024],1024);
ds.receive(dp);
int len = dp.getLength();
System.out.println(new String(dp.getData(),0,len));
}
}
运行结果:
UDP传输在笔者看来就是个”送快递”的过程,DatagramSocket看作一个快递站点,DatagramPacket看作是快递的货箱,需要传输的byte数组是我们要寄出的包裹。
这样设定好后我们来看发送端代码:
new DatagramSocket()就是随便找到一个快递站点,当然也可以指定站点(比如往里写端口号),str.getBytes()是我们要送的包裹,同时要知道包裹的体积或重量(str的长度)以及接收人和目的地(InetAddress与port),放入了快递货箱DatagramPacket里, send方法开始送货。
再看接收端代码:
同样是一个快递站点,但这个站点必须要指定了,也就是不可用new DatagramSocket()随便找站点,我们指定了8888端口号。DatagramPacket为一个给定容量的货箱(比如1024个字节),用receive方法开始接收。测试时先运行接收端,再运行发送端。这样就实现了UDP的简单传输。
(ps:需要注意的是像发送端代码写的str.length(),只适合发英文,改成str.getBytes().length最好)
基于以上代码,我们可以做个简单聊天界面:
代码如下:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.net.*;
import java.util.Calendar;
import javax.swing.*;
public class UDPDemo {
private static JTextArea view;
private static JTextArea sendTA;
private static JButton sendB;
private static Box northBox;
private static JFrame jf;
private Box southBox;
private JTextField jtf;
private DatagramSocket ds;
private DatagramSocket dsr;
public static void main(String[] args) throws Exception {
new UDPDemo();
}
UDPDemo() throws Exception{
initialJFrame();
initialNorthBox();
initialSouthBox();
ds = new DatagramSocket();
dsr = new DatagramSocket(8888);
receive();
jf.add(northBox);
jf.add(southBox,BorderLayout.SOUTH);
jf.setVisible(true);
}
private void initialSouthBox() {
southBox = Box.createHorizontalBox();
jtf = new JTextField("");
sendB = new JButton("发送");
sendB.addActionListener(new sendBActionListener());
southBox.add(jtf);
jtf.setPreferredSize(new Dimension(80,0));
southBox.add(sendB);
}
private void initialNorthBox() {
northBox = Box.createVerticalBox();
view = new JTextArea();
JScrollPane jsview = new JScrollPane(view);
jsview.setPreferredSize(new Dimension(0,180));
view.setEditable(false);
sendTA = new JTextArea();
JScrollPane jssendTA = new JScrollPane(sendTA);
northBox.add(jsview);
northBox.add(Box.createVerticalStrut(5));
northBox.add(jssendTA);
}
private void initialJFrame() {
jf = new JFrame();
jf.setBounds(250,100,500,500);
jf.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
private class sendBActionListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
try {
send();
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
public void send() throws Exception {
if(sendTA.getText().length()==0) return ;
DatagramPacket dp = new DatagramPacket(sendTA.getText().getBytes(),
sendTA.getText().getBytes().length,
InetAddress.getByName(jtf.getText().trim()),
8888);
ds.send(dp);
view.append(Calendar.getInstance().get(Calendar.HOUR_OF_DAY)+":"
+Calendar.getInstance().get(Calendar.MINUTE)+"\n"+
sendTA.getText()+"\n");
sendTA.setText("");
}
public void receive() throws Exception {
new Thread() {
public void run() {
while(true) {
DatagramPacket dp = new DatagramPacket(new byte[1024],1024);
try {
dsr.receive(dp);
view.append(Calendar.getInstance().get(Calendar.HOUR_OF_DAY)+":"
+Calendar.getInstance().get(Calendar.MINUTE)+"\n"+
new String(dp.getData(),0,dp.getLength())+"\n");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}.start();
}
}
附(Java网络编程学习资料):http://t.cn/Ex4YBPX