DatagramSocket编程

来源:互联网 发布:淘宝客服真的好忙好累 编辑:程序博客网 时间:2024/05/16 18:56
import java.awt.BorderLayout;import java.awt.Container;import java.awt.FlowLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.io.IOException;import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.InetAddress;import java.net.SocketException;import java.net.UnknownHostException;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JPanel;import javax.swing.JTextArea;import javax.swing.JTextField;public class Talk extends JFrame{JLabel la=new JLabel("请输入");JTextField tfd=new JTextField(20);JButton but=new JButton("发送");JPanel p=new JPanel();JTextArea jta=new JTextArea(10,20);Container c;DatagramSocket ds;DatagramReceive dc;int localPost=3000;int remotePost=5000;boolean flag=true;public void init(){c=this.getContentPane();c.setLayout(new BorderLayout());p.setLayout(new FlowLayout());p.add(la);p.add(tfd);p.add(but);c.add(p,BorderLayout.NORTH);c.add(jta,BorderLayout.CENTER);but.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){String temp=tfd.getText();jta.append("\n我说:"+temp);byte[] buf=temp.getBytes();try {DatagramPacket dp=new DatagramPacket(buf,buf.length,InetAddress.getByName("localhost"),remotePost);try {ds.send(dp);} catch (IOException e1) {// TODO Auto-generated catch blocke1.printStackTrace();}if(temp.trim().equals("bye")){flag=false;//dc.close();}} catch (UnknownHostException e1) {// TODO Auto-generated catch blocke1.printStackTrace();}}});this.setSize(500,500);this.setVisible(true);}public Talk(String name,int localPost,int remotePost){super(name);this.localPost=localPost;this.remotePost=remotePost;init();try {ds=new DatagramSocket(localPost);dc=new DatagramReceive(name,ds,jta);dc.start();} catch (SocketException e) {// TODO Auto-generated catch blockSystem.out.println("DatagramSocket创建失败");}}public static void main(String[] args) {Talk t1=new Talk("A",3000,5000);Talk t2=new Talk("B",5000,3000);}}


import java.io.IOException;import java.net.DatagramPacket;import java.net.DatagramSocket;import javax.swing.JTextArea;public class DatagramReceive extends Thread{String name;DatagramSocket ds;JTextArea jta;boolean flag=true;public DatagramReceive(String name,DatagramSocket ds,JTextArea jta){this.name=name;this.ds=ds;this.jta=jta;}public void run(){while(flag){byte[] buf=new byte[1024];DatagramPacket dp=new DatagramPacket(buf,buf.length);try {ds.receive(dp);String temp=new String(buf,0,dp.getLength());jta.append("\n对方说:"+temp);if(temp.trim().equals("bye")){flag=false;ds.close();}} catch (IOException e) {// TODO Auto-generated catch blockSystem.out.println(name+"接受失败");}}}}


原创粉丝点击