黑马程序员_java学习笔记七 网络编程篇

来源:互联网 发布:怎样的穿着叫淘宝风 编辑:程序博客网 时间:2024/05/01 21:25
---------------------- android培训、java培训、期待与您交流! ----------------------

网络编程的实质就是两个(或多个)设备(例如计算机)之间的数据传输。网络编程技术是当前一种主流的编程技术,随着联网趋势的逐步增强以及网络应用程序的大量出现,所以在实际的开发中网络编程技术获得了大量的使用。

   UDP编程:

import java.awt.* ;import java.awt.event.* ;import java.net.* ;import java.text.SimpleDateFormat;import java.util.Date;import javax.swing.* ;public class Adu extends JFrame {private static final long serialVersionUID = 1L;private JTextArea tArea01 ;private JTextArea tArea02 ;private JButton sendButton ;private JButton closeButton ;private JScrollPane sp1,sp2 ;private DatagramSocket s1 = null ;private DatagramSocket s2 = null ;public static int port = 11111 ;public Adu(){Gui() ;String string ;try {string = InetAddress.getByName(InetAddress.getLocalHost().getHostAddress()).toString() ;System.out.println(string);} catch (UnknownHostException e2) {// TODO Auto-generated catch blocke2.printStackTrace();}sendButton.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {try {s1 = new DatagramSocket() ;} catch (SocketException e1) {e1.printStackTrace();}byte[] buf = new byte[1024] ;buf = tArea02.getText().getBytes() ;try {DatagramPacket dPacket = new DatagramPacket(buf, buf.length, /*InetAddress.getLocalHost()*/InetAddress.getByName(InetAddress.getLocalHost().getHostAddress()), port) ;s1.send(dPacket) ;tArea02.setText("") ;tArea02.requestFocus() ;} catch (Exception e1) {e1.printStackTrace();}}}) ;closeButton.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubSystem.exit(0) ;s1.close() ;s2.close() ;}}) ;tArea02.addKeyListener(new KeyAdapter() {public void keyPressed(KeyEvent e){if(e.getKeyCode()==KeyEvent.VK_ENTER){try {s1 = new DatagramSocket() ;} catch (SocketException e1) {e1.printStackTrace();}byte[] buf ;buf = tArea02.getText().getBytes() ;try {DatagramPacket dPacket = new DatagramPacket(buf, buf.length, /*InetAddress.getLocalHost()*/InetAddress.getByName(InetAddress.getLocalHost().getHostAddress()), port) ;s1.send(dPacket) ;tArea02.getInputMap().put(                                KeyStroke.getKeyStroke("ENTER "), "none ");tArea02.setText("") ;tArea02.requestFocus() ;} catch (Exception e1) {e1.printStackTrace();}}}}) ;this.addWindowListener(new WindowAdapter()   {    public void windowClosing(WindowEvent w)    {           if(JOptionPane.showConfirmDialog(null,"是否要退出?","退出",JOptionPane.YES_NO_OPTION)==JOptionPane.YES_OPTION)      {       dispose();       System.exit(0);       s1.close();       s2.close() ;      }      if(JOptionPane.showConfirmDialog(null,"是否要退出?","退出",JOptionPane.YES_NO_OPTION)==JOptionPane.NO_OPTION)      {      Adu.this.setVisible(true) ;      }    }   });receiveData() ;}private void receiveData() {try {s2 = new DatagramSocket(port) ;} catch (SocketException e1) {// TODO Auto-generated catch blocke1.printStackTrace();}new Thread(new Runnable()   {       public void run()    {     byte buf[] = new byte[1024];         //表示接受数据报包     while(true)     {      try      {       DatagramPacket dPacket = new DatagramPacket(buf,1024);       s2.receive(dPacket);       tArea01.append("【消息来自】◆" + dPacket.getAddress().getHostAddress() + "◆在"+ Tools.getTime() +"【说】:"        + new String (buf,0,dPacket.getLength()) + "\r\n");             }            catch(Exception e)      {      if(s2.isClosed())          {           e.printStackTrace();          }      }     }     }    }).start() ;}public static void main(String arg[]){new Adu() ;}public void Gui(){this.setTitle("聊天窗口") ;Container container = getContentPane() ;container.setLayout(null) ;tArea01 = new JTextArea() ;tArea01.setBounds(0, 0, 550, 300) ;tArea01.setBackground(Color.yellow) ;tArea01.setEditable(false) ;tArea01.setLineWrap(true) ;tArea02 = new JTextArea("Type \"大家都来围观我吧\" here") ;tArea02.setBounds(0, 315, 550, 150) ;tArea02.setLineWrap(true) ;sendButton = new JButton("发送") ;sendButton.setBounds(250, 470, 75, 40) ;closeButton = new JButton("关闭") ;closeButton.setBounds(400, 470, 75, 40) ;this.setSize(600, 550) ;this.setLocation(200, 200) ;this.setUndecorated(true);this.getRootPane().setWindowDecorationStyle(JRootPane.FRAME);container.add(tArea01) ;container.add(tArea02) ;container.add(sendButton) ;container.add(closeButton) ;this.setVisible(true) ;tArea02.requestFocus() ;}}class Tools{         //获取当前时间         public static String getTime()          {                  Date date =new Date();                  SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");                  return sdf.format(date);         }}

在该示例代码中,首先建立UDP方式的网络连接,然后获得当前系统时间,这里获得的系统时间是客户端程序运行的本地计算机的时间,然后将时间字符串以及服务器端的IP和端口,构造成发送数据包对象,点击sendButton发送; 接收端接受数据包, 然后将信息显示在文本域中!

----------------------android培训、java培训、期待与您交流! ----------------------
原创粉丝点击